为什么不能将具体类添加到具体类实现的接口列表中?

问题描述 投票:-1回答:1

我在将实现接口的类的实例添加到该接口的列表时遇到麻烦;我收到类型验证错误。

我有以下内容:

  • 包含所有宠物共有的两个字段的基类PetPetIdName
  • 接口PetInterface强制执行两个字段:PetIdName
  • Dog继承并实现Cat的具体类PetPetInterface

代码:

public interface PetInterface
{
  public int PetId { get; set; }
  public string Name { get; set; }
}

public class Pet
{
  public int PetId { get; set; }
  public string Name { get; set; }
}

public class Dog: Pet, PetInterface
{
}

public class Cat: Pet, PetInterface
{                  
}

方案1:

var dog = new Dog();
var cat = new Cat();

List<PetInterface> petInterfaceList = new List<PetInterface>();

petInterfaceList.Add(dog1); //Error: cannot convert Dog to PetInterface class
petInterfaceList.Add(cat1); //Error: cannot convert Cat to PetInterface class

方案2:

var dog = new Dog();
var cat = new Cat();
var petList = new List<Pet>({dog, cat});

List<PetInterface> petInterfaceList = petList //Error: cannot convert List<Pet> to List<PetInterface>

我在这里想念什么?

c# interface polymorphism conceptual
1个回答
0
投票
  1. 我认为您的示例代码不会编译。
  2. 您没有在接口属性,方法上设置访问级别,将没有publicprivate,只有intString
  3. 您可能完全放弃了Interface并只继承了基类Pet。

        //The interface contract -> Assures these properties are part of base class
        public interface PetInterface
        {
            int petId { get; set; }
            String name { get; set; }
        }
    
        //base class which defines contract properties of interface PetInterface
        public class Pet : PetInterface
        {
            public int petId { get; set; }
            public String name { get; set; }
        }
    
        public class Dog: Pet
        {
           //Add dog specific properties/methods
        }
    
        public class Cat: Pet
        {
          //Add cat specific properties/methods
        }
    
© www.soinside.com 2019 - 2024. All rights reserved.