C# 在c中缓存反射属性及其自定义属性#
我使用一个自定义属性获取一个属性,然后根据另一个对象的值设置它的值-我使用反射获得如下属性: 类别属性:C# 在c中缓存反射属性及其自定义属性#,c#,asp.net,.net,reflection,C#,Asp.net,.net,Reflection,我使用一个自定义属性获取一个属性,然后根据另一个对象的值设置它的值-我使用反射获得如下属性: 类别属性: [MyPropertyName("MyString")] string myString { get; set; } 填充代码: public void PopulateMyPropertiesFromObject<T>(MyDataArrays dataArrays, T obj) where T : class, new() { Type type = t
[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);
}
}
}
public void populateMyProperties fromObject(MyDataArrays dataArrays,T obj),其中T:class,new()
{
类型=类型(T);
foreach(类型为.GetProperties()的PropertyInfo PropertyInfo)
{
foreach(PropertyInfo.GetCustomAttributes(true).OfType()中的MyPropertyName propName)
{
//从MyPropertyName与数组项的name属性匹配的数组中获取值
对象值=GetValue(DataArray,propName);
//将obj的propertyInfo的值设置为数组中匹配项的值
propertyInfo.SetValue(对象,值,空);
}
}
}
我有一个这些数据数组的集合,所以我在它们之间循环,实例化一个类型为T的新对象,并调用这个Populate方法来为集合中的每个项填充新的T
困扰我的是我在多大程度上查找MyPropertyName自定义属性,因为对该方法的每个调用都将为obj传递相同的类型。平均来说,这将发生25次,然后对象的类型将发生更改
有什么方法可以缓存带有MyPropertyName属性的属性吗?然后我就有一个属性+MyPropertyName的列表可以循环
或者我可以用比我更好的方式访问属性吗
对于上下文:这都发生在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;
}
//在进程上锁定PI,出于性能原因,reflectin数据在所有线程上收集一次。
私有静态对象_pilock=新对象();
私有静态字典(private static Dictionary);
公共属性INFO GetProperty(字符串logicalKey){
//先从dict开始试试
房地产信息;
//锁定对静电的访问,以确保螺纹安全
锁{
if(_propInfoDictionary.TryGetValue(logicalKey,out pi)){
返回pi;
}
pi=新财产信息;
//设置pi……在保存到字典中之前,尽一切努力准备对象
_添加(logicalKey,pi);
}//锁定期结束
返回pi;
}
将其存储在字典中,或使用备忘录(请参阅:)。感谢您的回复!现在,我将快速使用ConcurrentDictionary
,而不是使用锁来提高性能。