【问题标题】:Find generic object property attribute value using reflection at run time在运行时使用反射查找通用对象属性值
【发布时间】:2019-07-12 17:20:26
【问题描述】:

我创建了一个自定义属性类,用于在将对象导出为 CSV 格式时控制某些方面。

[AttributeUsage(AttributeTargets.Property)]
public class MyCustomAttribute : Attribute
{
    public bool Exportable { get; set; }
    public string ExportName{ get; set; }
}

这是我要导出的对象之一的示例:

public class ObjectA
{
    [MyCustom(Exportable = true, ExportColumnName = "Column A")]
    public string PropertyA {get; set; }

    [MyCustom(Exportable = false)]
    public string PropertyB {get; set; }

    public string PropertyC {get; set; }
}

我创建了接受通用对象的导出函数。

public void Export<T>(T exportObject)
{
   //I get the property name to use them as header
   var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

   foreach (var property in properties)
   {
      //find the list of attribute of this property.
      var attributes = Attribute.GetCustomAttributes(property, false);

     //if attribute "Exportable" value is false or doesn't exists then continue foreach
     //else continue export logic

   } 
}

我的问题是如何使用反射来查找属性是否具有“可导出”属性以及是否为真?

请注意,我可以传入任何通用对象,在这种情况下,我希望我的最终导出包含一个包含 PropertyA 数据的列,并且我的列标题值为“列 A”

【问题讨论】:

    标签: c# .net reflection


    【解决方案1】:

    你在正确的道路上,用这个替换 froeach 身体:

    var attribute = property.GetCustomAttribute<MyCustomAttribute>();
    
    if(attribute != null)
    {
      bool isExportable = attribute.Exportable;
      // rest of the code
    }
    

    【讨论】:

      【解决方案2】:

      @Sohaib Jundi 给出了非常好的答案。 如果出于某种原因,您决定创建更多自定义属性,您可以做一些类似这样的想法:

      public void Export<T>(T exportObject)
      {
          var properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
      
          foreach (var property in properties)
          {
              var attributes = Attribute.GetCustomAttributes(property, false);
      
              foreach (var attribute in attributes)
              {
                  if (attribute is MyCustomAttribute)
                  {
                      if (((MyCustomAttribute)attribute).Exportable)
                      {
      
                      }
                  }
      
                  if (attribute is MyCustomAttribute2)
                  {
                      if (((MyCustomAttribute2)attribute).AnotherThing)
                      {
      
                      }
                  }
              }
          }
      }
      

      这样您可以检查对象的多个属性

      【讨论】:

        猜你喜欢
        • 2015-11-01
        • 2016-01-24
        • 2015-05-02
        • 2011-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-11
        相关资源
        最近更新 更多