【问题标题】:caching reflected properties and their custom attributes in c#在 C# 中缓存反射属性及其自定义属性
【发布时间】: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 个属性,使用上面的属性用于上述方法的目的

【问题讨论】:

标签: c# asp.net .net reflection


【解决方案1】:

是的,您可以使用静态字典 为了安全地执行此操作,访问字典需要一个锁定期。 使其线程安全。

 // 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;
    }

【讨论】:

  • 感谢您的回复!我现在可以快速玩一下
  • 在这里使用ConcurrentDictionary 代替锁会提高性能。
猜你喜欢
  • 2017-05-31
  • 1970-01-01
  • 1970-01-01
  • 2021-03-24
  • 2012-02-05
  • 2010-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多