C# 使用对象的接口将对象列表强制转换为IList
我在从nuget包实现接口时遇到了一些问题。 接口中有一个类似这样的属性:C# 使用对象的接口将对象列表强制转换为IList,c#,.net,interface,casting,instance,C#,.net,Interface,Casting,Instance,我在从nuget包实现接口时遇到了一些问题。 接口中有一个类似这样的属性:IList实现{get;} 我的问题是从List转换到IList 这就是我试图做的,它给了我以下例外: 未处理的异常。System.NullReferenceException:对象引用未设置为对象的实例 使用系统; 使用System.Collections.Generic; 公共课程 { 公共静态void Main() { var ins1=newinterfaceinstance(){Id=“1”}; var ins2
IList实现{get;}
我的问题是从List
转换到IList
这就是我试图做的,它给了我以下例外:
未处理的异常。System.NullReferenceException:对象引用未设置为对象的实例
使用系统;
使用System.Collections.Generic;
公共课程
{
公共静态void Main()
{
var ins1=newinterfaceinstance(){Id=“1”};
var ins2=newinterfaceinstance(){Id=“2”};
List imps=new List(){ins1,ins2};
IList implements=imps作为IList;
foreach(工具中的var imp){
控制台写入线(imp.Id);
}
}
私有类接口实例:IInterfaceInstance
{
公共字符串Id{get;set;}
公共字符串名称{get;set;}
}
公共接口接口接口实例
{
公共字符串Id{get;set;}
公共字符串名称{get;set;}
}
}
IList
不是,因此您不能将列表
强制转换为IList
,并且您的as
运算符返回null
。如果您只想对项目进行迭代,请使用IEnumerable
。您不能像这样直接强制转换到IList
,因为它不是协变量。否则,您将能够将实现IInterfaceInstance
但不是InterfaceInstance
的内容添加到一个列表中,该列表应该只有InterfaceInstance
。相反,你必须像这样铸造每件物品
IList<IInterfaceInstance> implements = imps
.Cast<IInterfaceInstance>()
.ToList() as IList<IInterfaceInstance>;
IList implements=imps
.Cast()
.ToList()作为IList;
或者,您可以强制转换为IEnumerable
,因为它是共变的,因为它只允许您取出项目
IEnumerable<IInterfaceInstance> implements = imps as IEnumerable<IInterfaceInstance>;
IEnumerable implements=imps作为IEnumerable;
根据:
as运算符将表达式的结果显式转换为
给定的引用或可空值类型。如果转换不正确
可能的话,as运算符返回null
一般来说,泛型类型不允许其参数发生变化,这意味着您不能强制转换为其他类型。这就是为什么implements
为null,并且在尝试执行foreach
时失败的原因
为了达到您的目的,您必须将每个独立项转换为
IInterfaceInstance
,而不是整个列表。您可以使用linq选择一个新的ienumerable,传递lambda将每个接口实例转换为IInterfaceInstance
:
IList<IInterfaceInstance> implements = imps.Select(interfaceInstance => (IInterfaceInstance)interfaceInstance).ToList();
IList implements=imps.Select(interfaceInstance=>(IInterfaceInstance)interfaceInstance.ToList();
ILIst不是协变的,因此不能像那样强制转换泛型类型。您可以将其强制转换为IEnumerable
,因为您只能从IEnumerable
中获取项目。否则,您需要对每个项目进行强制转换才能使其正常工作。
IList<IInterfaceInstance> implements = imps.Select(interfaceInstance => (IInterfaceInstance)interfaceInstance).ToList();