【发布时间】:2012-11-13 14:13:32
【问题描述】:
我在使用 Visual Studio 10(现在也是 11)时遇到了一个奇怪的错误。我有一个扩展方法
public static S Foo<S, T>(this S s) where S : IEnumerable<T>
{
return s;
}
现在如果我打电话
"".Foo(); // => 'string' does not contain a definition for 'Foo' and no extension method 'Foo' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
我完全不明白引擎盖下发生了什么。恼人的部分是 intellisense 将 Foo 列为 IEnumberable<T>s。充其量它应该给出一个type can't be inferred error。
如果我这样称呼它:
Extension.Foo(""); // => The type arguments for method 'Extension.Foo<S,T>(S)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
为什么在上述情况下无法推断类型?
更多:
假设我有:
public static S Foo<S, T>(this S s, T t) where S : IEnumerable<T>
{
return s;
}
如果我打电话:
"".Foo(1);
类型推断在这里非常聪明地告诉我 Foo 应该返回 IEnumerable<int> 和 string 不是全部!!
所以如果编译器可以知道Foo 期望一个字符作为第一个参数,那么为什么我的第一个示例不直接编译呢? 换句话说,为什么在第一个示例中编译器知道 T 在这种情况下是 char?
正如预期的那样,这适用于第二个示例:
"".Foo('l');
我只是想知道为什么在第一个示例中不能将T 推断为char,毕竟字符串是IEnumberable<char>。
编辑:
我从 SLaks 那里得到了答案。但奇怪的是,考虑到编译器在公开可用方法对对象进行操作时,也考虑到了泛型约束,C# 没有这样做(类型推断)。
换句话说:
public static S Foo<S, T>(this S s)
{
return s;
}
使Foo 在所有objects 上可用。
public static S Foo<S, T>(this S s) where S : IEnumerable<T>
{
return s;
}
使Foo 在所有IEnumerable<T>s 上可用,因为它知道 S 是IEnumerable<T>。所以我在想 C# 甚至会推断出T 的类型!谢谢大家! ;)
【问题讨论】:
标签: c# visual-studio-2010 c#-4.0 type-inference