作者:龍城灬任少 | 来源:互联网 | 2023-08-04 10:46
从nuget包实现接口时遇到了一些问题。
界面中的属性如下所示:IList Implements {get;}
我的问题是从List
投射到IList
。
这是我要尝试的操作,它给了我以下异常:
未处理的异常。 System.NullReferenceException:对象引用未设置为对象的实例。
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var ins1 = new InterfaceInstance() {Id = "1"};
var ins2 = new InterfaceInstance() {Id = "2"};
List imps = new List() {ins1,ins2};
IList implements = imps as IList;
foreach( var imp in implements) {
Console.WriteLine(imp.Id);
}
}
private class InterfaceInstance : IInterfaceInstance
{
public string Id { get; set; }
public string Name { get; set; }
}
public interface IInterfaceInstance
{
public string Id { get; set; }
public string Name { get; set; }
}
}
按照documentation:
as运算符将表达式的结果显式转换为a
给定的引用或可为空的值类型。如果不是
可能,as运算符返回null。
通常,泛型类型不允许其参数有变化,这意味着您不能转换为其他类型。这就是implements
为null并在尝试执行foreach
时失败的原因。
要实现您的意图,您必须将每个独立项目强制转换为IInterfaceInstance
,而不是整个列表。
,
IList
不是covariant,因此无法将List
强制转换为IList
,并且as
运算符将返回null
。如果您要做的只是遍历所有项目,请改用IEnumerable
。
,
您不能像这样直接转换为IList
,因为它不是协变的。否则,您将可以添加实现IInterfaceInstance
但不是InterfaceInstance
的内容到只包含InterfaceInstance
的列表中。相反,您必须像这样投射每个项目。
IList implements = imps
.Cast()
.ToList() as IList;
您也可以强制转换为IEnumerable
,因为它是协变的,因为它只允许您拉出项目。
IEnumerable implements = imps as IEnumerable;
,
您可以使用linq选择一个新的枚举数,并传递一个lambda来将每个InterfaceInstance
转换为IInterfaceInstance
:
IList implements = imps.Select(interfaceInstance => (IInterfaceInstance)interfaceInstance).ToList();