如何在调用方法时从base获取派生类类型

时间:2016-06-14 15:37:41

标签: c# types

我搜索了互联网,并没有立即看到解决方案,应该很简单,但我不能弄明白。

我需要在只传入基类的方法中获取派生类Type:

class Base 
{
}

class Derived1 : Base
{
}

class Derived2 : Base
{
}

void SomeMethod(Base obj)
{
    Type baseType = obj.GetType();
    Type derivedType = obj.????
}

void Main()
{
    Base d1 = new Derived1();
    Base d2 = new Derived2();

    SomeMethod(d1);
    SomeMethod(d2);
}

2 个答案:

答案 0 :(得分:5)

.GetType()返回当前对象的实际类型。它不会返回基本类型。因此,如果您执行SomeMethod(new Derived1())obj.GetType()将返回Derived1(看起来这就是您想要的)。

答案 1 :(得分:1)

可能你想要这样的东西:

 using System.Reflection;
 ...

 void SomeMethod(Base obj) { 
   // Declared type, "Base" - since "Base obj" is declared in the method
   Type baseType = MethodInfo.GetCurrentMethod().GetParameters()[0].ParameterType;
   // Actual type, "Derived1", "Derived2" - actually passed as parameter
   Type derivedType = obj.GetType();
   ...
 }