在C#中,自定义属性是通过创建一个派生自System.Attribute类的新类来实现的。以下是一个简单的自定义属性的例子:
using System; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)] public class CustomAttribute : Attribute { public string Name { get; set; } public int Value { get; set; } public CustomAttribute(string name, int value) { Name = name; Value = value; } } [Custom("Attribute1", 1)] [Custom("Attribute2", 2)] public class MyClass { [Custom("MethodAttribute", 3)] public void MyMethod() { // Some code here } } 在上面的例子中,我们创建了一个名为CustomAttribute的自定义属性,并为其添加了Name和Value两个属性。然后我们在MyClass类和MyMethod方法上分别应用了CustomAttribute属性。
要访问自定义属性的值,可以使用反射来检索应用于类或方法的所有自定义属性,并获取其值,如下所示:
class Program { static void Main(string[] args) { Type type = typeof(MyClass); var classAttributes = type.GetCustomAttributes(typeof(CustomAttribute), false); foreach (CustomAttribute attribute in classAttributes) { Console.WriteLine($"Name: {attribute.Name}, Value: {attribute.Value}"); } var methodInfo = type.GetMethod("MyMethod"); var methodAttributes = methodInfo.GetCustomAttributes(typeof(CustomAttribute), false); foreach (CustomAttribute attribute in methodAttributes) { Console.WriteLine($"Name: {attribute.Name}, Value: {attribute.Value}"); } } } 以上代码将输出以下结果:
Name: Attribute1, Value: 1 Name: Attribute2, Value: 2 Name: MethodAttribute, Value: 3 这样就实现了在C#中创建和使用自定义属性的方法。