一个类如何实现两个接口中同名同参数不同返回值的函数
假设有如下两个接口:
public interface IA
{
string GetA(string a);
}
public interface IB
{
int GetA(string a);
}
他们都要求实现方法GetA,而且传入的参数都是一样的String类型,只是返回值一个是String一个是Int,现在我们要声明一个类X,这个类要同时实现这两个接口:
public class X:IA,IB
由于接口中要求的方法的方法名和参数是一样的,所以不可能通过重载的方式来解决,那么我们该如何同时实现这两个接口拉?解决办法是把其中的不能重载的方法直接写成接口的方法,同时要注意这个方法只能由接口调用,不能声明为Public类型的.所以X的定义如下:
public class X:IA,IB
{
public string GetA(string a)
{
Console.WriteLine("IA.GetA");
return a+":zengyi";
}
int IB.GetA(string a)//实现IB接口
{
Console.WriteLine("IB.GetA");
return 12;
}
}
同样如果有更多的同名同参不同返回值的接口,也可以通过"接口名.函数名"的形式实现.
调用方式如下:
public static void Main()
{
X a=new X();
a.GetA("studyzy");
IB b=a;
b.GetA("studyzy");
}
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
调用方式如下:
![](/Images/OutliningIndicators/None.gif)
![](/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/InBlock.gif)
![](/Images/OutliningIndicators/ExpandedBlockEnd.gif)
【本文章出自博客园深蓝居,转载请注明作者出处,如果您觉得博主的文章对您有很大帮助,欢迎支付宝(studyzy@163.com)对博主进行打赏。】