Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将接口数组强制转换为结构数组时,隐式强制转换无效_C#_Interface_Struct_Compiler Errors_Implicit Conversion - Fatal编程技术网

C# 将接口数组强制转换为结构数组时,隐式强制转换无效

C# 将接口数组强制转换为结构数组时,隐式强制转换无效,c#,interface,struct,compiler-errors,implicit-conversion,C#,Interface,Struct,Compiler Errors,Implicit Conversion,我有一个结构,它实现了一些接口。在我拥有一个struct实现的数组并尝试将该数组隐式转换为另一个接口类型的数组之前,这一切都很正常。(请参见下面的代码示例) 有一篇关于MSDN的好文章,我发现它非常有用。您在这里使用的Convariance不支持结构,因为它们是值类型而不是引用类型。有关更多信息,请参阅。数组方差ony允许保留引用的情况,因此仅适用于类。它本质上是将原始数据视为对不同类型的引用。这在结构中是不可能的。您的重复回答了您自己的问题。这个错误解释了这个错误,你试图做的是无效的C代码,解

我有一个
结构
,它实现了一些
接口
。在我拥有一个
struct
实现的数组并尝试将该数组隐式转换为另一个
接口类型的数组之前,这一切都很正常。(请参见下面的代码示例)


有一篇关于MSDN的好文章,我发现它非常有用。

您在这里使用的Convariance不支持结构,因为它们是值类型而不是引用类型。有关更多信息,请参阅。

数组方差ony允许保留引用的情况,因此仅适用于类。它本质上是将原始数据视为对不同类型的引用。这在结构中是不可能的。

您的重复回答了您自己的问题。这个错误解释了这个错误,你试图做的是无效的C代码,解决方法是使用一个类。@Ramhound我假设我做了一些在C#中无效的事情-我一直在寻找一个解释,或者对这样的解释的一些方向,正如我现在发现的那样。
using System.Collections.Generic;

namespace MainNS
{
    public interface IStructInterface
    {
        string Name { get; }
    }

    public struct StructImplementation : IStructInterface
    {
        public string Name
        {
            get { return "Test"; }
        }
    }

    public class MainClass
    {
        public static void Main()
        {
            StructImplementation[] structCollection = new StructImplementation[1]
            {
                new StructImplementation()
            };

            // Perform an implicit cast
            IEnumerable<IStructInterface> castCollection = structCollection;    // Invalid implicit cast
        }
    }
}
IEnumerable<IStructInterface> castCollection = structCollection.Cast<IStructInterface>();