ASP.NET MVC FIND CLASS BY CLASS ATTRIBUTE VALUE USING REFLECTION

Mark Devid

Total Post:102

Points:714
Posted by  Mark Devid
C# 
C#
 1233  View(s)
Ratings:
Rate this:

I have a class with a custom attribute that has a string parameter.

[ANAttribute("Ampe21")]
public class ClassB : ClassA
{
}

I have different action names defined for different classes.

What I want is to obtain the namespace of ClassB or obtain the type of ClassB by searching the entire application after Ampe21.

How can I do that?

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: ASP.NET MVC Find class by class attribute value using Reflection

    Hi Mark, 

    Try this:

    var types = AppDomain.CurrentDomain.GetAssemblies()
        .SelectMany(x =>x.GetTypes()
            .Where(t =>t.GetCustomAttribute<ANAttribute>() != null &&                    t.GetCustomAttribute<ANAttribute>().YourProperty =="Ampe21")
        );
    foreach (var type in types)
    {
        Console.WriteLine(type.Namespace);
    }

      Modified On Apr-04-2018 05:46:50 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!