c#-将接口数组转换为结构数组时,隐式强制转换无效
作者:互联网
我有一个实现某些接口的结构.直到我有一个struct实现的数组,并尝试将该数组隐式转换为接口类型的另一个数组,此方法才能正常工作. (请参见下面的代码示例)
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
}
}
}
编译上面的代码时,出现错误:
error CS0029: Cannot implicitly convert type ‘MainNS.StructImplementation[]’ to ‘MainNS.IStructInterface[]’
如果我将StructImplementation更改为一个类,则没有问题,因此我假设我尝试做的是无效的;或者我是盲人,缺少明显的东西.
任何建议或解释对此将不胜感激.
编辑
万一其他人遇到此问题并且使用其他方法不理想(如我所处的情况),我将使用LINQ方法Cast<T>()
解决我的问题.因此,在上面的示例中,我将使用某种方式执行强制转换喜欢:
IEnumerable<IStructInterface> castCollection = structCollection.Cast<IStructInterface>();
在MSDN上有一篇关于Variance in Generic Types的好文章,我发现它非常有用.
解决方法:
数组方差仅适用于保留引用的情况,因此仅适用于类.它实质上是将原始数据视为对其他类型的引用.使用结构根本不可能做到这一点.
标签:struct,compiler-errors,interface,implicit-cast,c 来源: https://codeday.me/bug/20191202/2085064.html