lundi 17 mai 2021

How to get attribute values from generic type? [duplicate]

I have a custom Attribute (MyAttribute) that has only one property named Name. So I am using in classes.

public class Product{
   
    [MyAttribute("product_name")]
    public string Name { get; set; }

    [MyAttribute("product_price")]
    public decimal Price { get; set; }
}

So I have a method to get attribute values and join them.

    public static IEnumerable<string> Method<T>(string separator = ",")
    {

        PropertyInfo[] properties = typeof(T).GetProperties();

        yield return string.Join(separator, properties
               .Where(p => p.GetCustomAttribute<MyAttribute>() != null)
               .Select(p => p.GetCustomAttribute<MyAttribute>().Name).ToArray());

    }

This works but I want to use as generic the attribute type. But can not get the Name property

    public static IEnumerable<string> Method<T, TAttribute>(string separator = ",")
    {

        PropertyInfo[] properties = typeof(T).GetProperties();

        yield return string.Join(separator, properties
               .Where(p => p.GetCustomAttribute<TAttribute>() != null)
               .Select(p => p.GetCustomAttribute<TAttribute>().??????(Name)).ToArray());

    }




Aucun commentaire:

Enregistrer un commentaire