问题描述
class Drawer
{
public abstract void Draw<T>(T type);
}
派生类#1
class ADrawer : Drawer
{
public override void Draw<T>(List<T> list)
{
foreach (var a in list)
{
DrawA(a);
}
}
public void DrawA(Agent a)
{
//draw code here
}
}
派生类#2
class AnotherDrawer : Drawer
{
public override void Draw<T>(T number)
{
if (number == 1)
{
//draw code
}
}
}
错误在 #1 派生类中:找不到合适的方法来覆盖"
The error is in the #1 derived class : "no suitable method found to override"
我应该如何设置基参数类型以允许派生类中的各种参数?
How should I set the base parameter type to allow a variety of parameters in derived classes?
推荐答案
您的代码有更多问题,而不仅仅是您询问的问题.暂时搁置覆盖问题,类 ADrawer 需要一个类型约束(where T : Agent
):
Your code has more problems than just the one you ask about. Setting aside the override question for the moment, class ADrawer needs a type constraint (where T : Agent
):
class ADrawer : Drawer
{
public void Draw<T>(List<T> list) where T : Agent
{
foreach (var a in list)
{
DrawA(a);
}
}
public void DrawA(Agent a)
{
//draw code here
}
}
如果没有这个约束,将 a
传递给 DrawA
是不合法的,因为 a
是 T类型的引用code>,没有约束就没有从
T
类型到 Agent
类型的隐式转换.
Without that constraint, it's not legal to pass a
to DrawA
, because a
is a reference of type T
, and without the constraint there is no implicit conversion from type T
to type Agent
.
AnotherDrawer 类非法使用了 ==
运算符.不能将 ==
运算符应用于 T
和 int
类型的操作数.您可以通过使用 object.Equals
覆盖来解决这个问题.
The AnotherDrawer class has an illegal use of the ==
operator. It's not possible to apply the ==
operator to operands of type T
and int
. You could get around that by using the object.Equals
override.
最后,基类有错误,因为它是一个包含抽象成员的非抽象类.
Finally, the base class has an error because it is a non-abstract class containing an abstract member.
然而,一般来说,这段代码表明类应该是通用的,而不是方法:
In general, however, this code indicates that the class should be generic, rather than the method:
abstract class Drawer<T>
{
public abstract void Draw(T type);
}
派生类#1
class ADrawer : Drawer<List<Agent>>
{
public override void Draw(List<Agent> list)
{
foreach (var a in list)
{
DrawA(a);
}
}
public void DrawA(Agent a)
{
//draw code here
}
}
派生类#2
class AnotherDrawer : Drawer<int>
{
public override void Draw(int number)
{
if (number == 1)
{
//draw code
}
}
}
要跟进 Eric Lippert 的评论,这也是我对您的问题的第一反应,您可以考虑改为使用此设计:
To follow up on Eric Lippert's comment, which was also my first reaction to your question, you might consider this design instead:
abstract class Drawer<T>
{
public abstract void Draw(T type);
public void DrawMany(IEnumerable<T> types)
{
foreach (var t in types)
Draw(t);
}
}
派生类#1
class ADrawer : Drawer<Agent>
{
public override void DrawA(Agent a)
{
//draw code here
}
}
派生类 #2 没有改变.
Derived class #2 is unchanged.
这篇关于覆盖非泛型类的抽象泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!