繁体   English   中英

从具有不同名称的成员实现接口成员

[英]Implementing interface member from member with a different name

说我有界面:

interface IThingWithId 
{
    int Id { get; }
}

...和一个班级:

partial class Dog 
{
    public int DogId { get; set; }
}

我想扩展Dog ,使其实现接口IThingWithId ,但是Dog的'id'具有不同的名称。 我曾希望这能起作用:

partial class Dog : IThingWithId {
    public int Id { get; }

    public Dog() {
        Id = DogId;
    }
}

但是没有运气,我得到的错误是

Dog没有实现接口成员IThingWithId.Id

这是否可能,或者我需要为Dog for Id添加一个单独的成员吗?

您需要添加一个单独的成员。 但是,您至少可以使用显式接口实现来“隐藏” Dog用户的ID:

class Dog : IThingWithId
{
  int IThingWithId.Id => DogId;

  public int DogId { get; }
}

现在您满足了界面:

IThingWithId dog = new Dog();
Console.WriteLine(dog.Id);    // works
Console.WriteLine(dog.DogId); // doesn't work, not part of IThingWithId

同时保持Dog的公共界面简单:

Dog dog = new Dog();
Console.WriteLine(dog.Id);    // doesn't work
Console.WriteLine(dog.DogId); // works

在CLR级别上,可以将任意名称的成员映射到已实现接口的成员。 但是C#不允许这样做。

您唯一的选择是拥有一个重复的成员,但是您可以使其成为“显式接口实现”,这样它就不会干扰其他成员,例如,当您在IntelliSense中看到它们时。

class Dog : IThingWithId 
{
    // the desired members in your class

    public int DogId { get; set; }

    public Dog() 
    {
    }

    // the wrapper member required by the interface

    int IThingWithId.Id => DogId;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM