【发布时间】:2019-12-12 17:20:30
【问题描述】:
我在从 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; }
}
}
【问题讨论】:
-
IList 不是协变的,所以你不能像那样转换泛型类型。您可以将其转换为
IEnumerable<IItnerfaceInstance>,因为您只能从IEnumerable中获取项目。否则,您需要强制转换每个项目才能使其正常工作。
标签: c# .net interface casting instance