vendredi 12 juillet 2019

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"





Aucun commentaire:

Enregistrer un commentaire