如何在C#中自定义Attribute

   2024-10-01 2280
核心提示:在C#中自定义Attribute可以通过创建一个继承自System.Attribute类的新类来实现。下面是一个简单的示例代码:using System;[Attri

在C#中自定义Attribute可以通过创建一个继承自System.Attribute类的新类来实现。下面是一个简单的示例代码:

using System;[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]public class CustomAttribute : Attribute{    public string Description { get; set; }    public CustomAttribute(string description)    {        Description = description;    }}public class MyClass{    [CustomAttribute("This is a custom attribute")]    public void MyMethod()    {        Console.WriteLine("Executing MyMethod");    }}class Program{    static void Main()    {        MyClass myClass = new MyClass();        var method = typeof(MyClass).GetMethod("MyMethod");        var attribute = (CustomAttribute)Attribute.GetCustomAttribute(method, typeof(CustomAttribute));        if (attribute != null)        {            Console.WriteLine(attribute.Description);        }        myClass.MyMethod();    }}

在以上示例中,我们首先定义了一个名为CustomAttribute的自定义属性类,并在其构造函数中初始化一个Description属性。然后,我们在MyMethod方法上应用了这个自定义属性。在Main方法中,我们使用Attribute.GetCustomAttribute方法来获取MyMethod方法上的CustomAttribute属性,并打印出其Description属性的值。

这是一个简单的示例,你可以根据自己的需求扩展自定义属性的功能和用法。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号