抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

C# Attribute用法

内建功能

标记函数

比如标记函数已过时,再调用这个函数时会有绿色的波浪线,并提示你函数已过时

[Obsolete("This func is obsolete, use newFunc()")]
public void OldFunc()
{
// do something
}

数据验证

可以确保某个数据存在

public class UserModel
{
[Required(ErrorMessage = "Username is required.")]
public string Username { get; set; }

[Required(ErrorMessage = "Password is required.")]
public string Password { get; set; }
}
// 创建一个对象,但是没有填充Required信息
var invalidUser = new UserModel();
var validationResults = new List<System.ComponentModel.DataAnnotations.ValidationResult>();
bool isValid = Validator.TryValidateObject(invalidUser, new ValidationContext(invalidUser), validationResults, true);
if (!isValid)
{
string errorMessage = string.Empty;
foreach (var validationResult in validationResults)
{
errorMessage +=validationResult.ErrorMessage;
}
// 输出 "Username is required.Password is required."
Console.WriteLine(errorMessage);
}

序列化与反序列化

WCF

Windows Communication Foundation

[DataContract]
public class Person
{
[DataMember]
public string Name { get; set; }

[DataMember]
public int Age { get; set; }
}
var person = new Person { Name = "John", Age = 20 };
var serializer = new DataContractSerializer(typeof(Person));
// 序列化
using (var memoryStream = new MemoryStream())
{
serializer.WriteObject(memoryStream, person);
memoryStream.Position = 0;
var serializedData = new StreamReader(memoryStream).ReadToEnd();
LabelText = serializedData;
}
// 反序列化
using (var reader = XmlReader.Create(new StringReader(LabelText)))
{
var deserializedPerson = (Person)serializer.ReadObject(reader);
}

序列化的产物是一个xml:

<Person xmlns="http://schemas.datacontract.org/2004/07/AttributeStudy" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><Age>20</Age><Name>John</Name></Person>

Serializable

[Serializable]
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Person person = new Person
{
Name = "John Doe",
Age = 30
};

// 序列化 Person 对象到文件
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Person));
using (var stream = new System.IO.FileStream("F:\\person.xml", System.IO.FileMode.Create))
{
serializer.Serialize(stream, person);
}

// 反序列化从文件读取的数据
using (var stream = new System.IO.FileStream("F:\\person.xml", System.IO.FileMode.Open))
{
Person deserializedPerson = (Person)serializer.Deserialize(stream);
Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}");
}

序列化产物是一个xml

<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Name>John Doe</Name>
<Age>30</Age>
</Person>

引入DLL

[DllImport("user32.dll")]
public static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type);

static void Main()
{
MessageBox(IntPtr.Zero, "Hello, World!", "Message", 0);
}

自定义功能

插件

自定义属性

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class PluginAttribute : Attribute
{
public string Name { get; }

public PluginAttribute(string name)
{
Name = name;
}
}

自定义的属性都形如xxxAttribute,在使用时只需要[xxx(“…”)]

插件接口和插件实现

public interface IPlugin
{
void Execute();
}

[Plugin("MyPlugin")]
public class MyPlugin : IPlugin
{
public void Execute()
{
Console.WriteLine("MyPlugin is executing.");
}
}

[Plugin("MyPlugin2")]
public class MyPlugin2 : IPlugin
{
public void Execute()
{
Console.WriteLine("MyPlugin2 is executing.");
}
}

找到所有插件,并执行所有插件

List<IPlugin> plugins = new List<IPlugin>();
// 获取所有插件类型
var pluginTypes = Assembly.GetExecutingAssembly().GetTypes()
.Where(type => type.GetCustomAttributes(typeof(PluginAttribute), true).Length > 0);
// 实例化插件
foreach (var pluginType in pluginTypes)
{
var pluginAttribute = (PluginAttribute)Attribute.GetCustomAttribute(pluginType, typeof(PluginAttribute));
var plugin = (IPlugin)Activator.CreateInstance(pluginType);

Console.WriteLine($"Loaded plugin: {pluginAttribute.Name}");
plugins.Add(plugin);
}
// 插件执行
foreach (var plugin in plugins)
{
plugin.Execute();
}

评论