2014-05-21 21 views
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(); 
     } 
+0

我不完全理解你的問題,你想從DownloadDataRequest獲取類型嗎?或者擁有這些屬性的方法/類的類型? –

+0

我想要的DownloadDataRequestHandler類型,如果我RequestHandlerCreator.CreateDataHandler(「DownloadDataRequest」) – Tomtom

回答

1

好吧,這是我會怎麼做:

public Type CreateDataHandler(string requestName) 
    { 
     Assembly _assembly = Assembly.GetExecutingAssembly(); 
     foreach (Module _module in _assembly.Modules) 
     { 
      if (_module.GetTypes().Length > 0) 
      { 
       foreach(Type _type in _module.GetTypes()) 
       { 
        if (_type.CustomAttributes.Count() > 0) 
        { 
         CustomAttributeData _customAttribute = _type.CustomAttributes.SingleOrDefault(a => a.AttributeType == typeof(DataExchangeItem)); 
         if (_customAttribute != null) 
         { 
          foreach (var _argument in _customAttribute.ConstructorArguments) 
          { 
           if (_argument.Value.ToString() == requestName) 
           { 
            return _type; 
           } 
          } 
         } 
        } 
       } 
      } 
     } 
     return null; 
    } 

讓我知道這是否正常工作了。