泛型函数创建参数base的泛型对象

Tij*_*enK 3 c# generics inheritance

我有以下代码:

public class Foo
{
    public void DoSomething()
    {
        DoSomething(this);
    }

    private static void DoSomething<T>(T obj)
    {
        var generic = new Generic<T>();
    }
}

public class Bar : Foo
{
    // properties/methods
}

public class Generic<T>
{
    // properties/methods
}

public class Test
{
    public void TestMethod()
    {
        var bar = new Bar();
        bar.DoSomething(); // instantiates Generic<Foo> instead of Generic<Bar>
    }
}
Run Code Online (Sandbox Code Playgroud)

是否可以使用当前类型而不是基类型从派生方法实例化泛型类?

Jon*_*eet 5

的编译时类型thisFoo.DoSomething只是Foo,所以编译器可以推断出类型参数的Foo.

根据执行时间类型获取它的最简单方法可能是:

DoSomething((dynamic) this);
Run Code Online (Sandbox Code Playgroud)

或者,你可以自己用反射来调用它.