我在将实现接口的类的实例添加到该接口的列表时遇到麻烦;我收到类型验证错误。
我有以下内容:
Pet
:PetId
和Name
。 PetInterface
强制执行两个字段:PetId
和Name
。Dog
继承并实现Cat
的具体类Pet
和PetInterface
。 代码:
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>
我在这里想念什么?
public
,private
,只有int
和String
您可能完全放弃了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
}