我有以下代码:
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.DoSomething
中 this
的编译时类型就是 Foo
,因此编译器只能 将类型参数推断为 Foo
。
让它根据执行时类型执行此操作的最简单方法可能是:
DoSomething((dynamic) this);
或者,您可以自己用反射来调用它。
关于c# - 通用函数创建参数基的通用对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23427698/