是否有一种设计模式可以将派生对象传递给基类方法而不进行强制转换?
是否有一种设计模式可以将以下代码重构为编译时类型安全的代码(即无类型转换)?
public abstract class Base1 {
public abstract void DoStuff(Base2 b);
}
public class Specific1 : Base1 {
public override void DoStuff(Base2 b) {
var s = (Specific2)b;
// do clever things with s
}
}
public abstract class Base2 { }
public class Specific2 : Base2 { }
Is there a design pattern that can refactor the following code into something that is type safe at compile-time (i.e. no type casting)?
public abstract class Base1 {
public abstract void DoStuff(Base2 b);
}
public class Specific1 : Base1 {
public override void DoStuff(Base2 b) {
var s = (Specific2)b;
// do clever things with s
}
}
public abstract class Base2 { }
public class Specific2 : Base2 { }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看起来您可能需要在这里考虑双重调度,即调用
b。
)。Specific1#DoStuff()
中的 DoStuff(Base1
不应该对如何处理其他类变得太聪明。Looks like you might want to consider double dispatch here, i.e. have a call to
b.DoStuff(
) inSpecific1#DoStuff()
.Base1
shouldn't become too clever about what to do with other classes.在Java中你可以这样做:
In Java you can do:
如果您想要访问 Specific2 中引入的特定方法(因此未在其基类 Base2 中定义),则除了强制转换之外别无选择。
除非,您使用泛型(在 C# fe 中):
但是,这当然会对您的
Specific1
类造成限制,即您只能将Specific2
实例传递给>DoStuff
方法。If you want to access specific methods that are introduced in Specific2 (and thus not defined in its base class, Base2), you have no other option than to cast it.
Unless, you use generics (in C# f.e.):
But, this puts a limitation on your
Specific1
class of course, that is you can only passSpecific2
instances to theDoStuff
method.