[英]Casting List of objects to a IList with the interface of the object
我在從 nuget 包實現接口時遇到了一些問題。 接口中有一個屬性,看起來像這樣: IList<IInterfaceInstance> Implements {get;}
我的問題是從List<InterfaceInstance>
為IList<IInterfaceInstance>
。
這就是我想要做的,它給了我以下異常:
未處理的異常。 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<InterfaceInstance> imps = new List<InterfaceInstance>() {ins1, ins2};
IList<IInterfaceInstance> implements = imps as IList<IInterfaceInstance>;
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; }
}
}
根據文檔:
as 運算符將表達式的結果顯式轉換為給定的引用或可為空值類型。 如果無法進行轉換,則 as 運算符返回 null。
通常,泛型類型不允許其參數變化,這意味着您不能轉換為不同的類型。 這就是為什么implements
為 null 並且在嘗試執行foreach
時失敗的原因。
為了實現您的意圖,您必須將每個獨立的項目轉換為IInterfaceInstance
,而不是整個列表。
您可以使用 linq 來選擇一個新的 ienumerable,傳遞一個 lambda 來將每個InterfaceInstance
為IInterfaceInstance
:
IList<IInterfaceInstance> implements = imps.Select(interfaceInstance => (IInterfaceInstance)interfaceInstance).ToList();
IList
不是covariant ,因此您不能將List<class>
IList<interface>
為IList<interface>
,並且您的as
運算符返回null
。 如果您只想遍歷項目,請改用IEnumerable<IInterfaceInstance>
。
您不能像那樣直接轉換為IList
,因為它不是協變的。 否則,您將能夠將實現IInterfaceInstance
但不是InterfaceInstance
到應該只有InterfaceInstance
的列表中。 相反,您必須像這樣投射每個項目。
IList<IInterfaceInstance> implements = imps
.Cast<IInterfaceInstance>()
.ToList() as IList<IInterfaceInstance>;
或者,您可以IEnumerable<IInterfaceInstance>
為IEnumerable<IInterfaceInstance>
因為它是協變的,因為它只允許您將項目拉出。
IEnumerable<IInterfaceInstance> implements = imps as IEnumerable<IInterfaceInstance>;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.