如何让抽象方法返回具有具体实现的抽象类型?
我有三个类,每个类都会返回略有不同的结果。
// interfact to a king
public interface IKing{
public Result Get();
}
// main abstract class
public abstract class King:IKing{
public abstract Result Get();
}
// main abstract result
public abstract class Result{
public int Type {get;set;}
}
// KingA result
public class ResultA:Result{
...
}
// KingB result
public class ResultB:Result{
...
}
// concrete implementations
public class KingA:King{
public override ResultA Get(){
return new ResultA;
}
}
public class KingB:King{
public override ResultB Get(){
return new ResultB
}
}
这将不起作用,因为 Get
的 King
重写方法需要 Result
类,并且不会接受其子 ResultA
和 ResultB
。
我可以采取更好的方法吗?
I have three classes that will each return a slightly different result.
// interfact to a king
public interface IKing{
public Result Get();
}
// main abstract class
public abstract class King:IKing{
public abstract Result Get();
}
// main abstract result
public abstract class Result{
public int Type {get;set;}
}
// KingA result
public class ResultA:Result{
...
}
// KingB result
public class ResultB:Result{
...
}
// concrete implementations
public class KingA:King{
public override ResultA Get(){
return new ResultA;
}
}
public class KingB:King{
public override ResultB Get(){
return new ResultB
}
}
This will not work since the King
overriden method of Get
is expecting the Result
class and will not accept its children ResultA
and ResultB
.
Is there a better approach I can take?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通常的方法是使用泛型。
编辑:固定语法。
The usual approach is to use generics.
Edit: fixed syntax.
如果您使用可编译的代码,将会有所帮助。您的“具体实现”是假的,看起来您混合了类和方法的概念。否则这里不存在设计问题。例如:
It will help if you use code that compiles. Your 'concrete implementations' are bogus, it looks like you mixed the concepts of class and method. There is otherwise no design problem here. For example:
我认为这里存在一些语法混乱——如果我正确地捕捉到了你的意图,那么这工作正常:(
编辑格式)
I think there's some syntax confusion here -- if I captured your intent correctly, this works fine:
(edited for formatting)
您应该能够在
Get
的实现中将ResultA
和ResultB
显式转换为Result
(我假设这就是“具体实现”的目的)。You should be able to explicitly cast
ResultA
andResultB
asResult
in the implementations ofGet
(I'm assuming that's what the "concrete implementations" are intended to be).