我正在使用自定义属性获取属性,然后根据另一个对象的值设置它的值 - 我正在使用反射来获取属性,如下所示:
类属性:
[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 个属性,出于上述方法的目的使用上述属性
最佳答案
是的,你可以,你可以使用静态字典 为了安全地这样做,访问字典需要一个锁定期。 使其成为线程安全的。
// 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;
}
关于c# - 在 C# 中缓存反射属性及其自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29749944/