温馨提示×

C#中如何自定义元数据属性

c#
小樊
87
2024-07-26 03:11:13
栏目: 编程语言

在C#中,可以通过创建自定义属性类来自定义元数据属性。以下是一个示例:

using System;

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class CustomAttribute : Attribute
{
    public string Description { get; set; }

    public CustomAttribute(string description)
    {
        Description = description;
    }
}

[CustomAttribute("This is a custom attribute")]
public class MyClass
{
    [CustomAttribute("This is a custom method attribute")]
    public void MyMethod()
    {
        // do something
    }
}

class Program
{
    static void Main()
    {
        Console.WriteLine("Custom attribute applied to class: " + typeof(MyClass).GetCustomAttributes(typeof(CustomAttribute), false)[0]);
        Console.WriteLine("Custom attribute applied to method: " + typeof(MyClass).GetMethod("MyMethod").GetCustomAttributes(typeof(CustomAttribute), false)[0]);
    }
}

在上面的示例中,我们创建了一个CustomAttribute类,它继承自Attribute类,并定义了一个Description属性。然后,我们在MyClass类和MyMethod方法上应用了CustomAttribute自定义属性。在Main方法中,我们可以使用反射来访问这些自定义属性并打印它们的值。

请注意,我们可以在CustomAttribute的构造函数中传递描述信息,并且我们可以通过AttributeUsage特性来指定自定义属性可以应用于哪些目标。

0