2015-04-20 56 views
2

我使用一個自定義屬性搶屬性,然後設置它是基於另一個對象的價值價值 - 我使用反射來獲取這樣的屬性:緩存反映屬性和C#中的自定義屬性

類屬性:

[MyPropertyName("MyString")] 
string myString { get; set; } 

填充代碼:

public void PopulateMyPropertiesFromObject<T>(MyDataArrays dataArrays, T obj) where T : class, new() 
    { 
     Type type = typeof (T); 

     foreach (PropertyInfo propertyInfo in type.GetProperties()) 
     { 
      foreach (MyPropertyName propName in PropertyInfo.GetCustomAttributes(true).OfType<MyPropertyName>()) 
      { 
      //Get the value from the array where MyPropertyName matches array item's name property 
      object value = GetValue(dataArrays, propName); 

      //Set the value of propertyInfo for obj to the value of item matched from the array 
      propertyInfo.SetValue(obj, value, null); 

      } 
     } 
    } 

我有這些數據陣列的集合,所以我循環通過這些實例化一個新objec t類型並調用這個Populate方法來爲集合中的每個項目填充新的T.

什麼是我查找MyPropertyName自定義屬性的多少,因爲每次調用此方法將傳入相同類型的obj。平均而言,這會發生25次,然後將對象的類型將改變

有什麼辦法,我可以緩存他們MyPropertyName屬性屬性?然後,我只希望有屬性+ MyPropertyNames循環列表通過

或者我可以以比我更好的方式訪問屬性嗎?

對於背景:一個asp.net網站的這一切發生服務器端,我有大約200-300的對象,每個使用上述方法的目的屬性大約50性能上面

+1

將其存儲在字典中,或使用記憶(請參閱:http://stackoverflow.com/a/2852595/261050)。 – Maarten

回答

2

是的,你可以,你可以使用一個靜態字典 要安全地這樣做,訪問字典需要一個鎖定時間段。 使線程安全。

// lock PI over process , reflectin data is collected once over all threads for performance reasons. 
private static Object _pilock = new Object(); 
private static Dictionary<string, PropertyInfo> _propInfoDictionary; 


public PropertyInfo GetProperty(string logicalKey) { 

     // try from dict first 
     PropertyInfo pi; 

     // lock access to static for thread safety 
     lock (_pilock) { 
      if (_propInfoDictionary.TryGetValue(logicalKey, out pi)){ 
       return pi; 
      }  


     pi = new PropertyInfo; 
     // set pi ...... do whatever it takes to prepare the object before saving in dictionary 
      _propertyInfoDictionary.Add(logicalKey, pi);  

     } // end of lock period 

     return pi; 
    } 
+0

感謝您的迴應!我現在快速玩一下 – Alex