我使用自定义属性来抓取属性,然后根据另一个对象的值设置它的值 - 我使用反射来获取如下属性:<\ n / p>
类属性:
[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);
}
}
}
我有这些数据数组的集合,因此我循环遍历它们,实例化一个T类型的新对象,并调用此Populate方法为集合中的每个项目填充新的T.
告诉我的是我查找MyPropertyName自定义属性的程度,因为对此方法的每次调用都将以相同的类型传递给obj。在平均值上,这将发生25次,然后对象的类型将改变
有没有办法可以使用MyPropertyName属性缓存属性?然后我只需要一个属性列表+ MyPropertyNames来循环
或者我可以以比我更好的方式访问属性吗?
对于上下文:这是asp.net网站上发生的所有服务器端,我有大约200-300个对象,每个对象使用上面的属性约50个属性用于上述方法
答案 0 :(得分: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;
}