簡體   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