C 中自定義Attribute值的獲取與優化

2021-07-09 01:42:28 字數 2781 閱讀 7103

c#

自定義attribute值的獲取是開發中會經常用到的,一般我們的做法也就是用反射進行獲取的,**也不是很複雜。

1、首先有如下自定義的attribute

[attributeusage(attributetargets.all)]

public sealed class nameattribute : attribute

}public nameattribute(string name)

}

2、定義乙個使用nameattribute的類

[name("dept")]

public class customattributes

[name("deptment address")]

public string address;

}

3、獲取customattributes類上的"dept"也就很簡單了

private static string getname()

return ((nameattribute)attribute).name;

}

以上**就可以簡單的獲取,類上的attribute的值了,但是需求往往不是這麼簡單的,不僅要獲取類頭部attribute上的值,還要獲取欄位address頭部attribute上的值。有的同學可能就覺得這還不簡單呀,直接上**

private static string getaddress()

var attribute = fieldinfo.getcustomattributes(typeof(nameattribute), false).firstordefault();

if (attribute == null)

return ((nameattribute) attribute).name;

}

上面**就是獲取address欄位頭部上的attribute值了。雖然我們是獲取到了我們想要的,但是我們發現這樣做是不是太累了,如果又擴充套件乙個自定義的attribute,或者又在乙個新的屬性或字段上標上attribute時,我們又要寫一段**來實現我想要的,這些嚴重**違反了dry的設計原則。我們知道獲取attribute是通過反射來取的,attribute那個值又是不變的,這樣就沒必要每次都要進行反射來獲取了。基於以上兩點**進行了如下的優化,優化後的**如下:

public static class customattributehelper

/// /// 獲取customattribute value

///

/// attribute的子型別

/// 頭部標有customattribute類的型別

/// 取attribute具體哪個屬性值的匿名函式

/// field name或property name

/// 返回attribute的值,沒有則返回null

public static string getcustomattributevalue(this type sourcetype, funcattributevalueaction,

string name) where t : attribute

private static string getattributevalue(type sourcetype, funcattributevalueaction,

string name) where t : attribute

return cache[key];

}/// /// 快取attribute value

///

private static void cacheattributevalue(type type,

funcattributevalueaction, string name)}}

private static string getvalue(type type,

funcattributevalueaction, string name)

else

var fieldinfo = type.getfield(name);

if (fieldinfo != null)

}return attribute == null ? null : attributevalueaction((t) attribute);

}/// /// 快取collection name key

///

private static string buildkey(type type, string name)

return type.fullname + "." + name;

}}

以上優化後的**:

把不同的**用泛型t,fun來處理來減少重複的**;

把取過的attribute值存到乙個dictionary中,下次再來取時,如果有則直接返回dictionary中的值,如果沒有才通過反射來取相應的attribute值,這樣大大的提高效率;

呼叫方法也更加的簡單了,**如下:

var cname=typeof(customattributes).getcustomattributevalue(x => x.name);

var fname = typeof (customattributes).getcustomattributevalue(x => x.name, "address");

有沒有, 是不是很簡單,而且呼叫方式對快取是完全透明的!

C 自定義特性Attribute要點

新增乙個特性類 其中attributeusage 可以修飾此特性類可修飾的型別 類命名後面習慣以 attribute 結尾,如類名display後面加attribute作為類名,就是displayattribute,此類要繼承attribute,建立乙個建構函式,帶乙個 string 引數,用以初始...

自定義Attribute的使用

attribute類是所有屬性型別的基類。個人理解attribute型別的主要作用是為某些需要進行特殊注釋的型別快速新增備註資訊。例如 using system using system.collections.generic using system.reflection 標示某個方法是否是aja...

理解自定義特性 Attribute

假設 外語老師 是乙個類,那麼 外語老師 應該具有這樣的特性 會說外語 並且 會說外語 這一特性又包含一些資訊,比如 外語種類 外語水平 其它資訊。按照這樣的理解,應該有下面的實現。using system using system.reflection namespace test console...