小编Tij*_*enK的帖子

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

我有以下代码:

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)

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

c# generics inheritance

3
推荐指数
1
解决办法
70
查看次数

标签 统计

c# ×1

generics ×1

inheritance ×1