在try 实现泛型时,我注意到具有实现接口的泛型的类与具有扩展基类的泛型的类之间存在不同的行为.使用接口时,我不能调用接受接口类型的可枚举数的函数,但使用类时,一切都很好.下面是一个例子
public interface IBarInterface
{
public int Value { get; set; }
}
public class FooInterface<TInterface> where TInterface : IBarInterface
{
private List<TInterface> _items;
public List<TInterface> Items => _items;
// Does not compile:
// Argument type 'System.Collections.Generic.List<TInterface>' is not assignable to parameter type 'System.Collections.Generic.IEnumerable<IBarInterface>'
public bool SomeValue => Processors.DoSomethingInterface(_items);
public FooInterface()
{
_items = new List<TInterface>();
}
}
public class BarClass
{
public int Value { get; set; }
}
public class FooClass<TClass> where TClass : BarClass
{
private List<TClass> _items;
public List<TClass> Items => _items;
// Does compile
public bool SomeValue => Processors.DoSomethingClass(_items);
public FooClass()
{
_items = new List<TClass>();
}
}
public static class Processors
{
public static bool DoSomethingInterface(IEnumerable<IBarInterface> items)
=> items.Count() % 2 == 0;
public static bool DoSomethingClass(IEnumerable<BarClass> items)
=> items.Count() % 2 == 0;
}
FooInterface
无法编译,但FooBar
编译得很好.为何会是这样呢?