C# 在C语言中实现2个类似的接口#
是否可以按如下方式实现以下2个接口?这段代码可以编译,但在阅读了如何实现这些代码之后,我不确定这是否有效C# 在C语言中实现2个类似的接口#,c#,interface,C#,Interface,是否可以按如下方式实现以下2个接口?这段代码可以编译,但在阅读了如何实现这些代码之后,我不确定这是否有效 Interface1 { Authorize(string p1, int p2); LookupCode(int test); GetObject(int ID); } Interface2 { Authorize(string p1); LookupCode(int test); GetObject(int ID); } class WebServ
Interface1
{
Authorize(string p1, int p2);
LookupCode(int test);
GetObject(int ID);
}
Interface2
{
Authorize(string p1);
LookupCode(int test);
GetObject(int ID);
}
class WebService : Interface1, Interface2
{
Authorize(string p1, int p2)
{
}
Authorize(string p1)
{
}
LookupCode(int test)
{
}
GetObject(int ID)
{
}
}
由于Authorize方法具有不同的签名,它们是否可以正确映射到正确的接口
其他相同的方法具有相同的实现,并且在类WebService中只有一个实例。这也行吗
由于Authorize方法具有不同的签名,它们是否可以正确映射到正确的接口
当然。事实上,这就是为什么它们可以正确地映射到各自的接口,而不是同时映射到两个接口的其他两种方法
注意:中的代码有明显的语法错误。然而,由于您提到您的代码是编译的,我假设您的实际代码已经修复了这些错误
由于Authorize方法具有不同的签名,它们是否可以正确映射到正确的接口
当然。事实上,这就是为什么它们可以正确地映射到各自的接口,而不是同时映射到两个接口的其他两种方法
注意:中的代码有明显的语法错误。但是,由于您提到您的代码是编译的,我假设您的实际代码已经修复了这些错误。如果您确实希望在两个接口中对相同的方法有不同的实现,您应该使用显式接口:
interface Interface1
{
void Authorize(string p1, int p2);
void LookupCode(int test);
void GetObject(int ID);
}
interface Interface2
{
void Authorize(string p1);
void LookupCode(int test);
void GetObject(int ID);
}
class WebService : Interface1, Interface2
{
public void Authorize(string p1, int p2)
{
throw new NotImplementedException();
}
public void Authorize(string p1)
{
throw new NotImplementedException();
}
void Interface2.LookupCode(int test)
{
throw new NotImplementedException();
}
void Interface2.GetObject(int ID)
{
throw new NotImplementedException();
}
void Interface1.LookupCode(int test)
{
throw new NotImplementedException();
}
void Interface1.GetObject(int ID)
{
throw new NotImplementedException();
}
}
但如果您不需要重复自己的操作,请使用如果您确实希望在两个接口中对同一方法有不同的实现,则应使用显式接口:
interface Interface1
{
void Authorize(string p1, int p2);
void LookupCode(int test);
void GetObject(int ID);
}
interface Interface2
{
void Authorize(string p1);
void LookupCode(int test);
void GetObject(int ID);
}
class WebService : Interface1, Interface2
{
public void Authorize(string p1, int p2)
{
throw new NotImplementedException();
}
public void Authorize(string p1)
{
throw new NotImplementedException();
}
void Interface2.LookupCode(int test)
{
throw new NotImplementedException();
}
void Interface2.GetObject(int ID)
{
throw new NotImplementedException();
}
void Interface1.LookupCode(int test)
{
throw new NotImplementedException();
}
void Interface1.GetObject(int ID)
{
throw new NotImplementedException();
}
}
但如果你不需要重复,当然可以使用。这意味着您可以在需要任何一个接口的任何地方使用此实现。如果您将
接口
关键字添加到接口中,这将起作用:是的,这些方法将正确映射,因为它们的签名…并声明返回类型。并且将实现方法公开(如果接口是内部的,则为内部的)。为什么不在这里尝试而不是询问呢?当然。这意味着您可以在需要任何一个接口的任何地方使用此实现。如果您将接口
关键字添加到接口中,这将起作用:是的,这些方法将正确映射,因为它们的签名…并声明返回类型。并且将实现方法公开(如果接口是内部的,则为内部的)。为什么不试试这个而不是在这里询问呢?这就是我的想法。由于其他方法只有一个实现,所以这些接口方法映射到何处并不含糊。上面的代码不是我正在使用的实际代码。我只是想展示一些相关的事实来回答我的问题。我就是这么想的。由于其他方法只有一个实现,所以这些接口方法映射到何处并不含糊。上面的代码不是我正在使用的实际代码。我只是想展示相关的事实来回答我的问题。