非通用类重写抽象泛型方法
class Drawer
{
public abstract void Draw<T>(T type);
}
派生类#1
derived class #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
derived class #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需要一个类型约束(其中T:代理
):
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
,且无约束有一个从类型的隐式转换 T
键入代理
。
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
derived class #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
}
}
}
要跟进埃里克利珀的评论,这是我也向你的问题的第一反应,你可能会考虑这样的设计来代替:
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
derived class #1
class ADrawer : Drawer<Agent>
{
public override void DrawA(Agent a)
{
//draw code here
}
}
派生类#2是不变的。