如何獲得程式中使用了某一自定義特性的所有型別。
例如:
有自定義特性:class MyAttribute: Attribute
我使用這個特性描述了函式foo
那么,我如何在main函式中獲得有哪些函式應用了MyAttribute特性?
uj5u.com熱心網友回復:
您需要收集所有程式集:ICollection <Assembly> baseAssemblies = AppDomain.CurrentDomain.GetAssemblies();
然後,對於每種類型的收集的程式集,您都可以使用此函數檢索與“ MyAttribute”相關的屬性名稱
公共靜態TValue GetAttributeValue <TAttribute,TValue>(此ICustomAttributeProvider類型,bool collectInheritedAttributes,Func <TAttribute,TValue> valueSelector),其中TAttribute:Attribute
{
var att = type.GetCustomAttributes(typeof(TAttribute),collectInheritedAttributes).FirstOrDefault()作為TAttribute;
如果(att!= null)
{
回傳valueSelector(att);
}
回傳default(TValue);
}
並以這種方式調用它:
字串名稱= <collectedType> .GetAttributeValue((MyAttribute dna)=> dna.Name);
再見!
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/250876.html
標籤:C#
上一篇:求vb.net或者c#生成三角概率分布和梯形概率分布亂數的代碼
下一篇:一個小時開發的直播推拉流軟體來了
