繁体   English   中英

在运行时使用反射查找通用对象属性的属性值

[英]Find generic object property attribute value using reflection at run time

我创建了一个自定义属性类,用于在将对象导出为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; }
}

我创建接受通用对象的Export函数。

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

   } 
}

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

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

您在正确的道路上,将泡沫体替换为:

var attribute = property.GetCustomAttribute<MyCustomAttribute>();

if(attribute != null)
{
  bool isExportable = attribute.Exportable;
  // rest of the code
}

@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)
                {

                }
            }
        }
    }
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM