【发布时间】:2015-04-20 13:56:35
【问题描述】:
我使用自定义属性来获取属性,然后根据另一个对象的值设置它的值 - 我使用反射来获取属性,如下所示:
类属性:
[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 个属性,使用上面的属性用于上述方法的目的
【问题讨论】:
-
将其存储在字典中,或使用记忆(参见:stackoverflow.com/a/2852595/261050)。
标签: c# asp.net .net reflection