覆盖继承的泛型方法 [英] Overriding inherited generic methods
问题描述
我在基类中的代码
protected virtual bool HasAnyStuff<TObject>(TObject obj) where TObject:class
{
return false;
}
在子类中,我重写
protected override bool HasAnyStuff<Customer>(Customer obj)
{
//some stuff
if Customer.sth etc
return false;
}
我收到此错误
I am getting this error
'''类型参数声明必须是一个标识符不是一个类型'''
'''Type parameter declaration must be an identifier not a type'''
这是什么,我做错了什么?
What is it I am doing wrong here?
推荐答案
您无法在派生类中重写泛型方法的类型参数。要实现类似的功能,一个选择是让你的基类是一个通用类,并有你的派生类,如
You can't override a generic method's type parameter in a derived class. To achieve a similar functionality, one option is to have your base class be a generic class, and have your derived class such as
class Derived : BaseClass<Customer>
{
protected override bool HasAnyStuff(Customer customer)
{
// ...
}
}
其中,的BaseClass
声明为
class BaseClass<T> where T : class
{
// ...
protected virtual bool HasAnyStuff(T obj)
{
// ...
}
}
此外,这取决于究竟是如何被使用的派生类中,你可以重写在 HasAnyStuff
方法用一个非通用客户
参数。
Alternatively, depending on exactly how your derived class is being used, you can just override the HasAnyStuff
method with a non-generic Customer
argument.
public bool HasAnyStuff(Customer customer)
{
// ...
}
不过,请注意,新的 HasAnyStuff
如果你不使用实例的工作将不会被调用 DerivedClass
。也就是说,
However, note that the new HasAnyStuff
will not be called if you are not working with an instance of DerivedClass
. That is to say,
BaseClass foo = new DerivedClass();
foo.HasAnyStuff(new Customer());
将调用的泛型方法的BaseClass
,不是的非泛型方法。 DerivedClass
will call BaseClass
's generic method, not DerivedClass
's non-generic method.
这篇关于覆盖继承的泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!