c# - 实现接口(interface)的结构与类

标签 c#

<分区>

private static void TestStructInterface()
{
    IFoo foo1 = new FooClass(); // works
    IFoo foo2 = new FooStruct(); // works
    IEnumerable<IFoo> foos1 = new List<FooClass>(); // works
    IEnumerable<IFoo> foos2 = new List<FooStruct>(); // compiler error
}

interface IFoo
{
    string Thing { get; set; }
}

class FooClass : IFoo
{
    public string Thing { get; set; }
}

struct FooStruct : IFoo
{
    public string Thing { get; set; }
}

编译器提示:

Cannot implicitly convert type 'System.Collections.Generic.List<Tests.Program.FooStruct>' to 'System.Collections.Generic.IEnumerable<Tests.Program.IFoo>'. An explicit conversion exists (are you missing a cast?)

为什么?
为什么类和结构之间存在差异? 有什么解决方法吗?

最佳答案

就像 Bharathram Attiyannan 回答的那样,值类型根本不支持方差。

解决方法很简单:

List<FooStruct> listOfFooStruct = new List<FooStruct>();
IEnumerable<IFoo> enumerableOfFoo = listOfFooStruct.Cast<IFoo>();

关于c# - 实现接口(interface)的结构与类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21231733/

相关文章:

c# - 为什么我不能将 Expression Body 转换为 MethodCallExpression

c# - 关闭已编程的应用程序后,系统句柄仍然存在。文件无法访问

c# - 如何证明多线程在工作?

c# - .Net 中的接口(interface)早期/晚期绑定(bind)

c# - "Data at the root level is invalid. Line 1, position 1"解析XML时

c# - 使用缓存键锁定缓存

c# - 以编程方式创建 packages.config

c# - Visual Studio IDE 对 var 关键字的含义感到困惑

c# - 应该如何在 WinForms GUI 控件和客户端类之间同步数据?

c# - 如何使用 Roslyn CTP 将行尾添加到 AttribueList