vendredi 8 mars 2019

Determine if an interface has a custom attribute

I've got a custom attribute:

public class InterfaceForPartialModelAttribute : Attribute
{
    //...
}

The attribute is applied to an interface (not on a property).

namespace DAL.Model
{
    [InterfaceForPartialModelAttribute] //<--custom attribute
    public interface IActivity_part
    { 
        string ActivityName { get; set; }
        ActivityTypeEnum ActivityType { get; set; }
        bool IsActivityDetailsCompleted { get; set; }
    }
}

Using reflections I want to scan the assembly and check for all interfaces that have my custom attribute:

Assembly[] assemblyArray = AppDomain.CurrentDomain.GetAssemblies();
var assTypes = assemblyArray[8].GetTypes(); //the 8th assembly is the one I've applied the attribute... this is irrelevant
string ns = "DAL.Model";
for (int i = 0; i < assTypes.Length; i++)
{
    bool hasDataContractAttribute = assTypes[i].GetCustomAttributes(typeof(InterfaceForPartialModelAttribute), true).Any();

    if (assTypes[i].IsInterface && assTypes[i].Namespace == ns && hasDataContractAttribute == true)
    {
        if (assTypes[i].Name == "IActivity_part")
        {
            Console.WriteLine("type found!");
        }


        Console.WriteLine("zr type: " + assTypes[i].Name);
        Console.WriteLine("zr ns  : " + assTypes[i].Namespace);
        Console.WriteLine("---------------------------------------------");

    }
}

The console does not print any result, hasDataContractAttribute is never true, how come? It seems that GetCustomAttributes returns attributes that are applied to properties. but I'm looking for attributes that are applied to the interface level. Most online example show how to get custom attributes by reflection on attributes.





Aucun commentaire:

Enregistrer un commentaire