简体   繁体   English

多态-使用从接口继承而不是直接从接口继承的对象

[英]Polymorphism - Using an object that inherits from an interface rather than the interface directly

In a C# class, is it possible to use a List<T> , where T is a class that implements an interface , but the List<T> is of a class that inherits from the interface , and not from the interface directly? 在C#类中,是否可以使用List<T> ,其中T是实现interface的类,但是List<T>是从interface继承的类,而不是直接从interface继承的类?

Here is some code to explain: 这是一些代码来解释:

public interface ITestClass
{
    List<IListItem> list { get; set; }
}

public interface IListItem
{
    //some data
}

public class ListItem : IListItem
{
    //some data
}

The following code compiles correctly: 以下代码正确编译:

public class TestClass : ITestClass
{
    public List<IListItem> list { get; set; }
}

However, the following code does not compile correctly: 但是,以下代码无法正确编译:

public class TestClass : ITestClass
{
    public List<ListItem> list { get; set; }
}

Can someone please explain why, and how I should modify my above code? 有人可以解释原因,以及如何修改上述代码吗?

The context of the situation is as follows: 情况的上下文如下:

I am wanting to serialize a TestClass object to file, however, it cannot be serialized with a List<T> where T is an interface . 我想将TestClass对象serialize文件,但是,不能使用List<T>序列化其中Tinterface I still want the ITestClass to specify that the list needs to inherit from IListItem if possible. 我仍然希望ITestClass尽可能指定list需要从IListItem inherit

Here is the serializtion code that I am using: 这是我正在使用的序列化代码:

IFormatter formatter = new BinaryFormatter(); 

Thanks 谢谢

You could make your interface take a generic type parameter and constrain it to types of IListItem : 您可以使您的接口采用通用类型参数,并将其约束为IListItem类型:

public interface ITestClass<T> where T : IListItem
{
    List<T> list { get; set; }
}

And now your TestClass becomes: 现在,您的TestClass变为:

public class TestClass : ITestClass<ListItem>
{
    public List<ListItem> list { get; set; }
}

As we don't know which serialiser you are using, here's an example with XML: 由于我们不知道您使用的是哪个序列化程序,因此下面是XML的示例:

//Set up the object to serialise
var testObject = new TestClass();
testObject.list = new List<ListItem>();
testObject.list.Add(new ListItem());

var serializer = new System.Xml.Serialization.XmlSerializer(typeof(TestClass));
StringWriter sw = new StringWriter();
XmlWriter writer = XmlWriter.Create(sw);
serializer.Serialize(writer, testObject);
var xml = sww.ToString();

And another example now you told us you are using the BinaryFormatter to serialise: 现在,您告诉我们另一个示例,您正在使用BinaryFormatter进行序列化:

var formatter = new BinaryFormatter();
var stream = new MemoryStream();

//Serialise the object to memory
formatter.Serialize(stream, testObject);

//Reset the position back to start of stream!
stream.Position = 0;

//Deserialise back into a new object
var newTestObject = (TestClass)formatter.Deserialize(stream);

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

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