我想覆盖派生类中的泛型方法。问题是我想要一个具体的类型参数实现,如下所示:
namespace Stumped
{
public class Generic<T> where T : new()
{
public virtual T Foo()
{
return new T();
}
public virtual TAnother GenericMethod<TAnother>() where TAnother : new()
{
return new TAnother();
}
}
public class Concrete : Generic<Inner1>
{
// Concrete return type. Works as expected.
public override Inner1 Foo()
{
return base.Foo();
}
// Why doesn't this make sense? Shows 'Type parameter "Inner2" hides class "Inner2"'.
public override Inner2 GenericMethod<Inner2>()
{
return base.GenericMethod<Inner2>();
}
}
public class Inner1 { }
public class Inner2 { }
}
如前所述,编译器告诉我:
Type parameter "Inner" hides class "Inner"
我希望我的实现能够工作,而不必在这个派生类中使用另一个通用参数。
为什么这没有意义?
最佳答案
你根本不能这样做。
重写方法不能更改方法接口(interface)的任何部分。由于GenericMethod<OtherClass>()
对基类有效,对派生类也必须有效。
这称为 Liskov substitution principle
.
正如编译器警告您的那样,您实际上只是声明了一个恰好与您的类同名的普通类型参数。
关于c# - 使用具体类型覆盖通用方法(类型参数 * 隐藏类 *),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37600275/