简体   繁体   中英

Find generic object property attribute value using reflection at run time

I created a custom attribute class that I use to control certain aspect when I export an object to CSV format.

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

Here is an example of one of the object I want to export:

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

I create my Export function that accept a generic object.

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

   } 
}

My question is how can I use reflection to find if the property has the attribute "Exportable" and that if it is true?

Please note I can pass in any generic object, in this case I want my final export to contain one column that contains PropertyA data and that my column header value is "Column A"

You are on the right path, replace the froeach body with this:

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

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

@Sohaib Jundi gave a very good answer. If, for some reason, you decide to create more Custom Attributes, you can do somethink similar to this:

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

                }
            }
        }
    }
}

This way you could check for multiple attributes of your object

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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