繁体   English   中英

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

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

在C#类中,是否可以使用List<T> ,其中T是实现interface的类,但是List<T>是从interface继承的类,而不是直接从interface继承的类?

这是一些代码来解释:

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

public interface IListItem
{
    //some data
}

public class ListItem : IListItem
{
    //some data
}

以下代码正确编译:

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

但是,以下代码无法正确编译:

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

有人可以解释原因,以及如何修改上述代码吗?

情况的上下文如下:

我想将TestClass对象serialize文件,但是,不能使用List<T>序列化其中Tinterface 我仍然希望ITestClass尽可能指定list需要从IListItem inherit

这是我正在使用的序列化代码:

IFormatter formatter = new BinaryFormatter(); 

谢谢

您可以使您的接口采用通用类型参数,并将其约束为IListItem类型:

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

现在,您的TestClass变为:

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

由于我们不知道您使用的是哪个序列化程序,因此下面是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();

现在,您告诉我们另一个示例,您正在使用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