C# “中的方法调用”;显式实现接口";班级
我想根据下面描述的上下文/场景来理解在C#中显式实现接口需要什么。假设我有以下界面:C# “中的方法调用”;显式实现接口";班级,c#,.net,inheritance,C#,.net,Inheritance,我想根据下面描述的上下文/场景来理解在C#中显式实现接口需要什么。假设我有以下界面: public interface ITestService { void Operation1(); void Operation2(); } 假设我如下图所示显式实现接口,是否可以使用任何方式从Operation1()调用Operation2() 下面不同声明的testService1和testService2的行为会有什么不同(包装下) static class Program {
public interface ITestService
{
void Operation1();
void Operation2();
}
假设我如下图所示显式实现接口,是否可以使用任何方式从Operation1()调用Operation2()
下面不同声明的testService1和testService2的行为会有什么不同(包装下)
static class Program
{
static void Main(string[] args)
{
ITestService testService1 = new TestService();
testService1.Operation1(); // => Works: WHY IS THIS POSSIBLE, ESPECIALLY SINCE Operation1() AND Operation2() WOULD BE *DEEMED* private?
// *DEEMED* since access modifiers on functions are not permitted in an interface
// while ...
TestService testService2 = new TestService();
testService2.Operation1(); //! Fails: As expected
}
}
关于你的第二个问题:
接口的所有成员都是公共的。因此,实施也将公开。关于第二个问题 testService1.Operation1();//=>Works:为什么这是可能的, 尤其是操作1()和操作2()将被视为 私人的 因为接口中的函数是公共的,所以可以调用它们。此外,如果已经显式实现了接口方法,则不能针对类对象调用它。e、 g
TestService ts = new TestService();
ts.Operation1();// this would cause an error
你可能会看到:好吧,这让我觉得自己很笨:)我从来没有想到我所需要做的就是把这一切都投入到IT服务中去。还是谢谢你,先生。
void ITestService.Operation1()
{
((ITestService)this).Operation2();
}
TestService ts = new TestService();
ts.Operation1();// this would cause an error