[英]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.