2015-04-20 55 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