c# - 多态性——使用从接口(interface)继承的对象而不是直接使用接口(interface)

标签 c# interface polymorphism

在 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; }
}

谁能解释一下为什么,我应该如何修改上面的代码?

事情的来龙去脉如下:

我想 serialize一个TestClass对象到文件,但是,它不能用 List<T> 序列化其中 T是一个 interface .我还是想要 ITestClass指定 list需要 inherit来自 IListItem如果可能的话。

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

IFormatter formatter = new BinaryFormatter(); 

谢谢

最佳答案

您可以让您的接口(interface)采用通用类型参数并将其限制为 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);

关于c# - 多态性——使用从接口(interface)继承的对象而不是直接使用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30885885/

相关文章:

java - 在 Erlang 中使用 Dialyzer 的行为来模拟接口(interface)

php - php 中的特征——任何真实世界的例子

java - 更改 NetBeans UI 外观/感觉

java - 多态性错误?

c# - WPF ComboBox 自动完成中的 SelectedItem

c# - 如何在 .NET Core 库中记录 Trace?

haskell - GADT 扩展会破坏多态性吗?

c++ - 组件系统的逆向转换

c# - 数组元素的反向波兰表示法。 (例如 : array_name[i, j])

c# - Windows 窗体应用程序 C# 发生了奇怪的事情