我正在尝试解码这个相当复杂的程序。
有一个名为IInterface_1的通用接口。它公开了一个方法,“MethodName”,它在方法签名中有一个参数。
public interface IInterface_1<S> where S : class, "ISomeClass", new()
{
S MethodName(IEnumerable<Ilistname> Name);
}
我希望继承IInterface_1的通用类或接口必须提供实现方法“MethodName”的实现或路径。如图所示,MethodName在方法签名中有一个参数。
但是,在程序的其他地方,相同的方法名称由另一个接口“IInterface_2”公开,其中方法签名中只有两个参数。在这两种情况下,约束都是相同的,除了IIinterface_2继承自IInterface_1。
public interface IInterface_2<S> : IInterface_1 where S : class, "ISomeClass", new()
{
S MethodName(IEnumerable<Ilistname> Name, ISomethingElse Name_2);
}
IInterface_2来自IInterface_1,但是IInterface_2和IInterface_1暴露了相同的方法但具有不同数量的参数。根据我对接口的了解,上面会违反接口“合同”,但这个程序运行正常。我错过了什么?
谢谢 汤姆
答案 0 :(得分:1)
当你的某些类实现IInterface_1
时,只需要实现S MethodName(IEnumerable<Ilistname> Name);
如果它正在实施IInterface_2
,则需要同时实施
S MethodName(IEnumerable<Ilistname> Name);
S MethodName(IEnumerable<Ilistname> Name, ISomethingElse Name_2);
因此,当您在应用程序中使用IInterface_2
抽象的对象时,您应该可以调用这两种方法。
它也不再是任何C#语法规则。您描述的接口有不同的名称。两个提到的方法都有相同的名称但不同的参数集。
Morover即使它们具有相同的参数,它也可能是有效的C#代码。尝试以下程序并检查写入控制台的内容。
public interface IBasicInterface
{
int Test();
}
public interface IAdvancedInterface : IBasicInterface
{
int Test();
}
public class AdvancedClass : IAdvancedInterface
{
int IBasicInterface.Test()
{
return 1;
}
int IAdvancedInterface.Test()
{
return 2;
}
}
class Program
{
static void Main(string[] args)
{
AdvancedClass tester = new AdvancedClass();
Console.WriteLine(((IAdvancedInterface)tester).Test()); // returns 2
Console.WriteLine(((IBasicInterface)tester).Test()); // returns 1
Console.ReadLine();
}
}
但是,我也很难说这种设计的用法很少。