重载抽象方法
考虑这个例子:
public interface IAccount
{
string GetAccountName(string id);
}
public class BasicAccount : IAccount
{
public string GetAccountName(string id)
{
throw new NotImplementedException();
}
}
public class PremiumAccount : IAccount
{
public string GetAccountName(string id)
{
throw new NotImplementedException();
}
public string GetAccountName(string id, string name)
{
throw new NotImplementedException();
}
}
protected void Page_Load(object sender, EventArgs e)
{
IAccount a = new PremiumAccount();
a.GetAccountName("X1234", "John"); //Error
}
如何从客户端调用重写的方法,而不必在抽象/接口上定义新的方法签名(因为这只是高级帐户的特殊情况)?我在这个设计中使用抽象工厂模式...谢谢...
Consider this example:
public interface IAccount
{
string GetAccountName(string id);
}
public class BasicAccount : IAccount
{
public string GetAccountName(string id)
{
throw new NotImplementedException();
}
}
public class PremiumAccount : IAccount
{
public string GetAccountName(string id)
{
throw new NotImplementedException();
}
public string GetAccountName(string id, string name)
{
throw new NotImplementedException();
}
}
protected void Page_Load(object sender, EventArgs e)
{
IAccount a = new PremiumAccount();
a.GetAccountName("X1234", "John"); //Error
}
How can I call the overridden method from the client without having to define a new method signature on the abstract/interface (since it is only an special case for the premium account)? I'm using abstract factory pattern in this design... thanks...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须将接口强制转换为特定的类。请记住,这会将接口的整个概念抛到九霄云外,并且您可以在所有情况下使用特定的类。考虑调整您的架构。
You will have to cast the interface to the specific class. Keep in mind that this would throw the whole concept of interfaces right out of the window and you could be using specific classes in all cases. Think about adjusting your architecture instead.
您将引用强制转换为特定类型:
You cast the reference to the specific type:
您可以使用这两种方法定义
IPremiumAccount
接口,并在 PremiumAccount 类中实现它。检查对象是否实现接口可能比检查特定基类更好。You can define
IPremiumAccount
interface with both methods and implement it the PremiumAccount class. Checking if an object implements the interface is probably better than checking for specific base class.好吧,考虑到它仅为
PremiumAccount
类型定义,您知道可以调用它的唯一方法是a
实际上是一个PremiumAccount
,对吧?因此,首先转换为PremiumAccount
:Well, considering it's only defined for the
PremiumAccount
type, the only way you know you can call it is ifa
is actually aPremiumAccount
, right? So cast to aPremiumAccount
first: