1

我正在研究一组相当复杂的接口,这些接口允许定义具有特定结构的对象。通过接口和泛型,它还允许我定义每个元素中可用的接口组合。该结构映射了我们背景中的某些内容,因此目标是在代码中重新创建结构,以便更好地理解代码实际操作的内容。

结果如下所示:

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();

}

现在在实现具体类时,我在 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;

}

尤其是这两行让我感到困扰(尤其是最后一行):

public IActorCompositionLevel2 ElementC => _actors;
IActorCompositionLevel1 IElementC<IActorCompositionLevel1>.ElementC => _actors;

第一行很清楚,正如我们所知

  [visibility] [Type]                  [Name]   => [what gets returned]
  public       IActorCompositionLevel2 ElementC => _actors;

第二行不具有相同的可见性(尽管两者都是公共的),并且类型定义更复杂,并且在名称前有一个额外的点(这是我到目前为止还没有看到的部分)。

IActorCompositionLevel1 IElementC<IActorCompositionLevel1>.ElementC
4

1 回答 1

5

在最后一行,我认为您正在寻找的是显式接口实现。如果您使用相同的方法实现 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

更多关于官方文档的内容。

=>表达式体成员,它基本上就像函数的简写,每次访问属性时都会调用该函数。您可以将其视为

IActorCompositionLevel1 IElementC<IActorCompositionLevel1>.ElementC {
    get {
        return _actors;
    }
}

手写,所以不要尝试编译。但它应该说明这一点

于 2021-10-08T10:21:37.570 回答