繁体   English   中英

反射:获取已初始化的自动属性的真实类型(C#6)

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

我有一个这样声明的类:

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

我想要使​​用反射的实现类型的列表。 我没有MyClass的实例,只是类型。

例如:

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:我不确定标题是否适合改编,但我发现没有什么比这更好的了。 我愿意提出建议。

反射是类型元数据的自省,因此,除非您提供所谓的类型的实例,否则它无法获取给定类型的实际实例可能包含在其属性中的内容。

这就是诸如PropertyInfo.GetValue类的反射方法具有第一个必填参数的主要原因:声明属性的类型的实例。

如果要为此使用反射,则方向错误。 实际上,您需要一个语法分析器 ,幸运的是,C#6随附了新的高级编译器,该编译器以前称为Roslyn(GitHub存储库) 您还可以使用NRefactory(GitHub存储库)

两者都可以用来解析实际的C#代码。 您可以解析整个源代码,然后获取表达式主体属性中返回的类。

没有类实例就无法获得实类型,因为属性仅针对实例进行初始化。 例如,您可以执行类似的操作

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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