C# 重载抽象方法
考虑这个例子:C# 重载抽象方法,c#,overloading,abstraction,C#,Overloading,Abstraction,考虑这个例子: public interface IAccount { string GetAccountName(string id); } public class BasicAccount : IAccount { public string GetAccountName(string id) { throw new NotImplementedException(); } } public class PremiumAccount :
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
}
我如何从客户端调用覆盖的方法,而不必在抽象/接口上定义新的方法签名(因为这只是保费帐户的特例)?我在这个设计中使用抽象工厂模式。。。谢谢…您必须将接口转换为特定类。请记住,这会将接口的整个概念抛到窗外,您可以在所有情况下使用特定的类。考虑调整您的体系结构。好吧,考虑到它只是为
PremiumAccount
类型定义的,您知道可以调用它的唯一方法是如果a
实际上是PremiumAccount
,对吗?因此,先将其转换为一个PremiumAccount
:
IAccount a = new PremiumAccount();
PremiumAccount pa = a as PremiumAccount;
if (pa != null)
{
pa.GetAccountName("X1234", "John");
}
else
{
// You decide what to do here.
}
将引用强制转换为特定类型:
((PremiumAccount)a).GetAccountName("X1234", "John");
您可以使用这两种方法定义
IPremiumAccount
接口,并将其实现为PremiumAccount类。检查对象是否实现了接口可能比检查特定的基类要好
public interface IPremiumAccount : IAccount
{
public string GetAccountName(string id, string name);
}
public class PremiumAccount : IPremiumAccount
{
// ...
IAccount a = factory.GetAccount();
IPremiumAccount pa = a as IPremiumAccount;
if (pa != null)
pa.GetAccountName("X1234", "John");
是的,正如我所说的,它只适用于特殊情况,因为抽象模式对于这样的特殊情况没有特定的解决方案……`IAccount a=new PremiumAccount();`因此,没有必要这样做cast@SaeedAlg你错了。引用的类型为
IAccount
,因此它不知道仅存在于PremiumAccount
中的方法。抱歉,方法名称相同:D