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

时间:2015-09-08 18:22:14

标签: c# .net reflection c#-6.0

我有一个像这样声明的类:

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:我不确定标题是否适应,但我没有找到更好的结果。我愿意接受建议。

2 个答案:

答案 0 :(得分:1)

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

这就是为什么像PropertyInfo.GetValue这样的反射方法有第一个必需参数的主要原因:声明属性的类型的实例。

如果您想使用反射,那么您的方向是错误的。 实际上你需要一个语法分析器,幸运的是,C#6附带了新的和花哨的编译器,以前称为Roslyn (GitHub repository)。您也可以使用NRefactory (GitHub repository)

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

答案 1 :(得分:0)

如果没有类实例,则无法获取实际类型,因为属性仅针对实例进行初始化。例如,你可以做类似的事情

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