【发布时间】:2016-01-29 09:39:17
【问题描述】:
在代码前完成问题:
为什么IEnumerable<T> where T : ITest 不被接受为期望this IEnumerable<ITest> 的扩展方法的接收者?
现在是代码:
我有三种类型:
public interface ITest { }
public class Element : ITest { }
public class ElementInfo : ITest { }
还有两种扩展方法:
public static class Extensions
{
public static IEnumerable<ElementInfo> Method<T>(
this IEnumerable<T> collection)
where T : ITest
{
→ return collection.ToInfoObjects();
}
public static IEnumerable<ElementInfo> ToInfoObjects(
this IEnumerable<ITest> collection)
{
return collection.Select(item => new ElementInfo());
}
}
我得到的编译器错误(在标记线上):
CS1929:'IEnumerable<T>'不包含'ToInfoObjects'的定义,并且最佳扩展方法重载'Extensions.ToInfoObjects(IEnumerable<ITest>)'需要'IEnumerable<ITest>'类型的接收器
为什么会这样? ToInfoObjects 扩展方法的接收者是IEnumerable<T>,并且通过泛型类型约束,T 必须实现ITest。
为什么接收方不被接受?我的猜测是IEnumerable<T> 的协方差,但我不确定。
如果我将ToInfoObjects 更改为接收IEnumerable<T> where T : ITest,那么一切正常。
【问题讨论】:
标签: c# .net generics extension-methods type-inference