首页 > 解决方案 > 从具有不同名称的成员实现接口成员

问题描述

说我有界面:

interface IThingWithId 
{
    int Id { get; }
}

......还有一个班级:

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

我想扩展Dog它以实现接口IThingWithId,但“id”的Dog名称不同。我曾希望这会奏效:

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

    public Dog() {
        Id = DogId;
    }
}

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

Dog不实现接口成员IThingWithId.Id

这是可能的,还是我需要为Dogfor添加一个单独的成员Id

标签: c#

解决方案


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

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

推荐阅读