【问题标题】:Why can't I add concrete classes to a list of interfaces which the concrete classes implement?为什么我不能将具体类添加到具体类实现的接口列表中?
【发布时间】:2020-02-14 17:03:56
【问题描述】:

我无法将实现接口的类的实例添加到该接口的列表;我收到类型验证错误。

我有以下几点:

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

代码:

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>

我在这里错过了什么?

【问题讨论】:

  • 让类Pet实现接口,然后继承DogCat中的Pet
  • C# 版本是什么:Inherits Pet || Implements PetInterface?
  • 您的代码似乎包含很多错别字。你能先修好它们吗?这包括但不限于:dog1cat1在第一个代码sn-p中应该是dogcat吧?
  • "var cat = new Dog();"你有一只迷糊的狗
  • 鉴于您拥有的(概念上),场景 1 应该可以正常工作(请参阅 this dotnetfiddle)。正如其他人指出的那样,场景2中的错误仅仅是因为PetPetInterface之间没有转换。

标签: c# interface polymorphism conceptual


【解决方案1】:
  1. 我认为您的示例代码不会编译。
  2. 你不设置接口属性、方法的访问级别,不会有publicprivate,只有intString
  3. 您可能完全取消接口并从基类 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
        }
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 2013-03-07
    • 2013-09-30
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 2011-12-23
    相关资源
    最近更新 更多