c# - 通用函数创建参数基的通用对象

标签 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>
    }
}

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

最佳答案

Foo.DoSomethingthis 的编译时类型就是 Foo,因此编译器只能 将类型参数推断为 Foo

让它根据执行时类型执行此操作的最简单方法可能是:

DoSomething((dynamic) this);

或者,您可以自己用反射来调用它。

关于c# - 通用函数创建参数基的通用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23427698/

相关文章:

java - 不使用 super 的子类方法的默认行为是什么?

c# - AutoMapper 和继承 - 如何映射?

c# - 保存使用 SaveFileDialog 动态创建的 word 文档?

C#如何调用参数数量未知的方法

c# - 不允许在查询中显式构造实体类型 ''

c# - PdfSharp XGraphics.DrawString 不适用于波斯语等从右到左的语言

java - 是否可以编写一个方法来接受不同抽象的通用参数?

c++ - std::shared_ptr 类工厂 C++

swift - Generic Decodable 停止使用 swift 4.1

Java:使用泛型作为抽象层