2009-01-21 81 views
2

我有一個從基類(BaseClass)繼承的類(Descendant1)。一個後代類的實例被傳遞給一個將BaseClass作爲參數的方法。然後使用反射,它會調用對象的屬性。如何獲得後裔類的屬性值

public class BaseClass { } 

public class Descendant1 : BaseClass 
{ 
    public string Test1 { get { return "test1"; } } 
} 


public class Processor 
{ 
    public string Process(BaseClass bc, string propertyName) 
    { 
     PropertyInfo property = typeof(BaseClass).GetProperty(propertyName); 
     return (string)property.GetValue(bc, null); 
    } 
} 

我的問題是這樣的。在Process方法中,是否有可能找出對象究竟是什麼(Descendant1),然後聲明該類型的對象(可能使用Reflection)並將BaseClass參數強制轉換爲該對象,然後對其執行反射雜技?

謝謝。

回答

6

我不知道如果我理解你的問題,但也許你是這樣想的東西:

 public string Process(BaseClass bc, string propertyName) 
     { 
      PropertyInfo property = bc.GetType().GetProperty(propertyName); 
      return (string)property.GetValue(bc, null); 
     } 

bc.GetType()得到真正類型的BC(當你通過Descendant1這將是Descendant1不BaseClass的)。

+0

這正是我的意思。非常感謝。 – AngryHacker 2009-01-21 18:21:24