[英]How can I get the properties of an inherited object when the parameter is declared as a base type?
我有一個簡單的程序,它使用反射打印出提供的類的屬性和值。
class BaseClass
{
public string A
{
get { return "BaseClass"; }
}
}
class Child1 : BaseClass
{
public string Child1Name {
get { return "Child1"; }
}
}
class Child2 : BaseClass
{
public string Child2Name
{
get { return "Child2"; }
}
}
class Program
{
static void Main(string[] args)
{
var child1 = new Child1();
var child2 = new Child2();
SomeMethod(child1);
SomeMethod(child2);
Console.ReadKey();
}
static void SomeMethod(BaseClass baseClass)
{
PrintProperties(baseClass);
}
static void PrintProperties<T>(T entity)
{
var type = typeof(T);
foreach (var targetPropInfo in type.GetProperties())
{
var value = type.GetProperty(targetPropInfo.Name).GetValue(entity);
Console.WriteLine("{0}: {1}", targetPropInfo.Name, value);
}
Console.WriteLine("");
}
}
問題是它只打印出BaseClass
屬性,因為我使用泛型並將BaseClass
傳入PrintProperties
方法。
輸出:
答:BaseClass
答:BaseClass
如何訪問Child類的屬性? 我想要一個輸出像:
答:BaseClass
Child1Name:Child1答:BaseClass
Child2Name:Child2
這里的問題是你在PrintProperties
使用typeof(T)
,但是你的例子中的T
是BaseClass
因為這是你從SomeMethod
給出的參數的類型。
在您的示例中,刪除SomeMethod
,直接調用PrintProperties
方法,它將工作。
一種更簡單的方法是使用entity.GetType()
而不是typeof(T)
。 這樣,無論泛型類型是什么,您都將始終獲得對象的真實類型。
這里的問題是你使用泛型然后提取泛型類型值的屬性。
泛型允許您執行在運行時填充的一些元編碼(實際上是JIT時間),但是對泛型的調用在編譯時處理泛型推理 。 因此,因為您使用BaseClass
類型的變量調用PrintProperties
,所以始終將T
推斷為BaseClass
, 而不是實際的運行時類型。
有兩種方法 - 一種是使用每個 object
都有的內置GetType()
方法。
var type = entity.GetType();
作為這個garunantees你將有運行時類型。
另一方面,對於需要完美泛型的其他情況,是使用dynamic
對象傳遞給泛型方法,這允許運行時在運行時推斷泛型類型,從而獲得完全匹配的類型:
static void SomeMethod(BaseClass baseClass)
{
PrintProperties((dynamic)baseClass);
}
typeof(T)
將返回該特定類型。 這意味着當T
是BaseClass
您只會獲得與之相關的屬性。 它不知道任何派生的東西。
你要做的是用entity.GetType()
替換typeof(T)
entity.GetType()
。 GetType()
返回對象實例的實際類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.