mon*_*nty 1 c# interface explicit-interface
我正在开发一组相当复杂的接口,它允许定义具有特定结构的对象。通过接口和泛型,它还允许我定义每个元素中可用的接口组合。该结构映射了我们背景中的某些内容,因此目标是在代码中重新创建结构,以便更好地理解代码实际操作的内容。
结果如下:
static void Main(string[] args)
{
IComplexDefinition1 CD1 = null;
CD1.Access.Level1.ElementB.SomeStructrueMethod();
CD1.Access.Level1.ElementC.ActorAMethod1();
CD1.Access.Level1.ElementC.ActorBMethod2();
CD1.Access.Level1.ElementC.ActorCMethod1();
CD1.Access.Level2.ElementA.SomeOperationPoolMethod();
CD1.Access.Level2.ElementC.ActorAMethod2();
CD1.Access.Level2.ElementC.ActorBMethod1();
CD1.Access.Level2.ElementC.ActorCMethod2();
}
Run Code Online (Sandbox Code Playgroud)
现在,在实现具体类时,我在 Visual Studio 中单击了“自动实现”,它出现了一行我到目前为止还没有看到的代码(并且没想到会发生这种情况)。因此,我正在寻找它的工作原理以及我可以在哪里阅读/研究更多相关信息的见解。
具体实现的相关部分是:
public class ComplexDefinition : IComplexDefinition1,....
{
protected IActorComposition _actors;
protected SomeStructure _structure;
protected SomeOperationPool _operationPool;
public IElementsBC<IActorCompositionLevel2, SomeStructure> Level1 => this;
public IElementsAC<IActorCompositionLevel1, SomeOperationPool> Level2 => this;
public SomeStructure ElementB => _structure;
public SomeOperationPool ElementA => _operationPool;
public IActorCompositionLevel2 ElementC => _actors;
IActorCompositionLevel1 IElementC<IActorCompositionLevel1>.ElementC => _actors;
}
Run Code Online (Sandbox Code Playgroud)
尤其是这两行让我感到困扰(尤其是最后一行):
public IActorCompositionLevel2 ElementC => _actors;
IActorCompositionLevel1 IElementC<IActorCompositionLevel1>.ElementC => _actors;
Run Code Online (Sandbox Code Playgroud)
正如我们所知,第一行很清楚
[visibility] [Type] [Name] => [what gets returned]
public IActorCompositionLevel2 ElementC => _actors;
Run Code Online (Sandbox Code Playgroud)
第二行不具有相同的可见性(尽管两者都是公共的),并且类型定义更复杂,并且在名称之前有一个额外的点(这是我到目前为止还没有看到的部分)。
IActorCompositionLevel1 IElementC<IActorCompositionLevel1>.ElementC
Run Code Online (Sandbox Code Playgroud)
在最后一行,我认为您正在寻找的是显式接口实现。如果您使用相同的方法实现 2 个不同的接口,那么您可以使用此构造来区分它们。
例如:
public class TestClass : IInterface1, IInterface2
{
void IInterface1.SameMethod()
{
System.Console.WriteLine("IInterface1");
}
void IInterface2.SameMethod()
{
System.Console.WriteLine("IInterface2");
}
}
// now if you create the class itself then the type you are assigning it into will decide what method it should call
TestClass test = new TestClass();
test.SameMethod(); // this won't compile, since it won't know what to call
(test as IInterface1).SameMethod(); // this should display "IInterface1" in console
Run Code Online (Sandbox Code Playgroud)
官方文档中有更多相关内容。
是=>
表达式主体成员,它基本上就像一个函数的简写,每次访问该属性时都会调用该函数。您可以将其视为简写
IActorCompositionLevel1 IElementC<IActorCompositionLevel1>.ElementC {
get {
return _actors;
}
}
Run Code Online (Sandbox Code Playgroud)
手写的,所以不要尝试编译它。但应该能说明问题