jeudi 15 mars 2018

How can I get the value of a property of all the classes that implements an interface? [duplicate]

This question already has an answer here:

I have the following architecture:

public interface IStatus
{
    string StatusName {get;}
}
public class A: IStatus
{
    public string StatusName {get {return "A Status";}}
}

public class B: IStatus
{
    public string StatusName {get {return "B Status";}}
}

public class C: IStatus
{
    public string StatusName {get {return "C Status";}}
}

I tried the following and I can see in debug all the relevant classes but I am not sure how to get the StatusName property for each one of the classes. I presume, I need to create an instance of each class somehow and ask for the StatusName property.

public class Test
{
    var type = typeof(IStatus);
    var types = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(s => s.GetTypes())
            .Where(p => type.IsAssignableFrom(p));

        foreach (Type mytype in types)
        {
            var i = mytype.GetMember("StatusName");
            if (i.Count()!=0)
            {
                var n = i.GetValue(0);
            }               
        }
}

The expected result I need is a list of string with values: "A Status", "B Status", "C Status"





Aucun commentaire:

Enregistrer un commentaire