0
我實現了一個屬性類,它看起來像自定義屬性:獲取類,其中CustomProperty的有一定價值
internal class DataExchangeItem : Attribute
{
public DataExchangeItem(string request)
{
Request = request;
}
public string Request { get; set; }
}
現在我有幾個班,我使用這個屬性,如:
[DataExchangeItem("DownloadDataRequest")]
internal class DownloadDataRequestHandler : IDataHandler
{ ... }
比我有一個靜態方法類似看起來像
public static Class RequestHandlerCreator
{
public static IDataHandler CreateDataHandler(string request)
{
switch(request){... // compare strings and give DataHandler}
}
}
現在我試圖取代switch語句和一個語句,在這裏我可以檢查所有類的屬性,然後在屬性Request-property中獲取具有我搜索到的請求字符串的類。
爲了讓在我的屬性被定義我使用所有Type
的List:
List<Type> customAttributes = (from type in Assembly.GetExecutingAssembly().GetTypes()
where type.GetCustomAttributes(typeof(DataExchangeItem),true).Length > 0
where type.GetCustomAttributesData().Count > 0
select type).ToList();
我知道我可以調用type.GetCustomAttributesData()
在Type
- Object
得到的CustomAttributeData
列表。每個CustomAttributeData
-屬性都比具有一個NamedArguments集合。
不幸的是,我不管理它以獲取Type
-我的搜索字符串的對象。現在
我的問題是:
我怎樣才能在裝配在我的自定義屬性是 類型定義,請求 - 酒店搜索我的價值?
由於荷蘭人。你的代碼有效。我在LINQ的聲明完全改變了它:
private static Type FindTypeForRequest(string request)
{
return (from module in Assembly.GetExecutingAssembly().Modules
where module.GetTypes().Length > 0
from type in module.GetTypes()
where type.CustomAttributes.Any()
let customAttribute = type.CustomAttributes.SingleOrDefault(a => a.AttributeType == typeof (DataExchangeItem))
where customAttribute != null
where customAttribute.ConstructorArguments.Any(argument => argument.Value.ToString() == request)
select type).FirstOrDefault();
}
我不完全理解你的問題,你想從DownloadDataRequest獲取類型嗎?或者擁有這些屬性的方法/類的類型? –
我想要的DownloadDataRequestHandler類型,如果我RequestHandlerCreator.CreateDataHandler(「DownloadDataRequest」) – Tomtom