2011-09-25 49 views
0

如何获取调用者类的基类?C#获取调用者类的类型(不是静态的)

这是父,在这里我要打印的子类型而不发送

public abstract class Parent: ISomeInterface { 

     public void printChildType() 
     { 
      Type typeOfMyChild = ?????; 
      MessageBox.Show(typeOfMyChild); //how do I get Child typeOfMyChild 
     } 
} 

孩子

public class Child : parent { 

} 

pirnt子类型:

Child child = new Child(); 
child.printChildType(); 

感谢

(I已经看到这一个:Get inherited caller type name in base static class但我没有用静态方法)

回答

2
Type typeOfMyChild = this.GetType(); 

感谢多态,当你调用:

Child child = new Child(); 
child.printChildType(); 

它应该打印Child

+3

这里没有必要让'printChildType'虚拟来观察多态。 – Ani

+0

@Ani,正确。感谢您指出了这一点。我已经更新了我的答案。 –

2

你不是在寻找当前的类型吗?

public void printChildType() 
    { 
     Type typeOfMyChild = GetType(); 
     MessageBox.Show(typeOfMyChild); 
    }