日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C#中屬性(Attribute)的用法_C#教程

作者:springsnow ? 更新時間: 2022-07-06 編程語言

一、創建屬性

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor, AllowMultiple = true, Inherited = true)]
//AttributeTargets:屬性應用到的目標類型。AllowMultiple:是否允許一個元素應用多個此屬性。Inherited:屬性能否有派生類繼承。
public class CodeStatusAttribute : Attribute
{
    private string status;
    public CodeStatusAttribute(string status)//構造函數為位置參數
    {
        this.status = status;
    }
    public string Tester { set; get; }//屬性和公共字段為命名參數
    public string Coder { set; get; }
    
    public override string ToString()
    {
        return status;
    }
}

二、應用屬性

//1、使用單個屬性
[CodeStatus("a版")]
public class Tringe
{ }

//2、使用多個屬性
[CodeStatus("b版", Coder = "小李")]
[CodeStatus("b版", Coder = "小王")]
//也可以[CodeStatus("aa",Coder="小李"),CodeStatus("aa",Coder="小王")]
public class Square
{ }

//3、使用位置參數和命名參數
//type表示此屬性與什么元素關聯,可能有:assembly,field,method,param,property,return,moudule,event,type等。。
[type: CodeStatus("最終版", Coder = "小李", Tester = "老李")]
public class Circle
{
    [CodeStatus("最終版", Coder = "小李", Tester = "老李")]
    public Circle()
    {

    }
}

三、反射屬性

//1、獲取類上的屬性。
Type t = typeof(Circle);
Attribute[] attArr = Attribute.GetCustomAttributes(t, typeof(CodeStatusAttribute));
//或
object[] attArr1 = t.GetCustomAttributes(typeof(CodeStatusAttribute), true);

//2、獲取成員上屬性
Attribute[] attArr3 = t.GetConstructors()[0].GetCustomAttributes().ToArray();//構造函數,獲取字段GetField("..")

//3、遍歷
foreach (Attribute attr in attArr3)
{
    CodeStatusAttribute item = (CodeStatusAttribute)attr;
    Console.Write(item.ToString() + item.Coder + item.Tester);
}

四、Net內置屬性

[Condeitonal] //條件控制
[Obsolete] //廢棄屬性
[Serializable]//可序列化屬性
[AssemblyDelaySign] //程序集延遲簽名

原文鏈接:https://www.cnblogs.com/springsnow/p/9433923.html

欄目分類
最近更新