[英]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>
序列化其中T
是interface
。 我仍然希望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.