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

Tiz*_*izz -1 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);
}
Run Code Online (Sandbox Code Playgroud)

And*_*rey 5

.GetType()返回当前对象的实际类型.它不返回基本类型.所以,如果你这样做SomeMethod(new Derived1()),obj.GetType()将返回Derived1(似乎这就是你想要的).