我有一个struct
来实现一些interface
。这工作正常,直到我有一个struct
实现的数组,并尝试隐式地将该数组转换为另一个interface
类型的数组。 (参见下面的代码示例)
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
}
}
}
编译上面的代码时,我收到错误:
错误CS0029:无法将类型'MainNS.StructImplementation []'隐式转换为'MainNS.IStructInterface []'
如果我将StructImplementation
更改为class
我没有问题,那么我假设我要做的事情要么无效;或者我是盲目的,并且遗漏了一些明显的东西。
对此有任何建议或解释。
修改
如果其他人遇到此问题且使用不同的方法并不理想(就像我的情况那样),我使用LINQ方法Cast<T>()
解决了我的问题。所以在上面的例子中,我将使用类似的东西执行演员表:
IEnumerable<IStructInterface> castCollection = structCollection.Cast<IStructInterface>();
关于Variance in Generic Types的MSDN上有一篇很好的文章,我觉得这篇文章很有用。
答案 0 :(得分:2)
数组方差ony允许引用保留大小写,因此仅适用于类。它基本上将原始数据视为对不同类型的引用。对于结构,这是不可能的。
答案 1 :(得分:1)
结构不支持您在此处使用的协方差,因为它们是值类型而不是引用类型。有关详细信息,请参阅here。