简体   繁体   中英

Reflection : Get the real type of a initialized auto-property (C#6)

I have a class declared like this :

public class MyClass
{
    public IMyInterface1 Prop1 { get; } = new MyImplementation1();
    public IMyInterface2 Prop2 { get; } = new MyImplementation2();
    public IMyInterface3 Prop3 { get; } = new MyImplementation3();
    //[...]
}

I would like the list of implemented types, using reflection. I dont have an instance of MyClass, just the type.

Ex:

static void Main(string[] args)
{
    var aList = typeof(MyClass).GetProperties(); // [IMyInterface1, IMyInterface2, IMyInterface3]
    var whatIWant = GetImplementedProperties(typeof(MyClass)); // [MyImplementation1, MyImplementation2, MyImplementation3]
}

IEnumerable<Type> GetImplementedProperties(Type type)
{
    // How can I do that ?
}

PS: I'm not sure the title is well adapted, but I have found nothing better. I am open to suggestions.

Reflection is type metadata introspection, thus, it can't get what an actual instance of a given type may contain in their properties unless you provide an instance of the so-called type.

That's the main reason why reflection methods like PropertyInfo.GetValue have a first mandatory argument: the instance of the type where the property is declared on.

You're in the wrong direction if you want to use reflection for this. Actually you need a syntax analyzer and luckily, C# 6 comes with the new and fancy compiler formerly known as Roslyn (GitHub repository) . You can also use NRefactory (GitHub repository) .

Both can be used to parse actual C# code. You can parse the whole source code and then get what classes are returned in expression-bodied properties.

You can't get real types without class instance, because properties are initialized only for instances. For instance of the class, you can do something like that

List<Type> propertyTypes = new List<Type>();
PropertyInfo[] properties = typeof(MyClass).GetProperties();
foreach(PropertyInfo propertyInfo in properties)
{
    propertyTypes.Add(propertyInfo.GetValue(myClassInstance));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM