gpt4 book ai didi

c# - 尽管 intellisense 列出了定义,但找不到定义?

转载 作者:太空狗 更新时间:2023-10-29 22:33:15 25 4
gpt4 key购买 nike

我在使用 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期待一个 char 作为第一个参数,那么为什么我的第一个例子不能编译? 换句话说,为什么在第一个例子中编译器知道 T在那种情况下是 char?

正如预期的那样,这适用于第二个示例:

"".Foo('l');

我只是想知道为什么不能 T被推断为char在第一个例子中,毕竟字符串是 IEnumberable<char> .


编辑:

我从 SLaks 那里得到了答案。但考虑到编译器在公开可用方法以对对象进行操作时也会考虑泛型约束,C# 不执行此操作(一种类型推断)真是太奇怪了。

换句话说:

public static S Foo<S, T>(this S s)
{
return s;
}

制造 Foo适用于所有object

public static S Foo<S, T>(this S s) where S : IEnumerable<T>
{
return s;
}

制造 Foo适用于所有IEnumerable<T>因为它知道 SIEnumerable<T> .所以我在想 C# 甚至会推断 T 的类型!谢谢大家! ;)

最佳答案

类型推断引擎不够智能,无法做到这一点。

C# 类型推断只看方法签名
Generic constraints are not part of the signature .

由于 T 没有直接在签名中使用,编译器不会推断它。

关于c# - 尽管 intellisense 列出了定义,但找不到定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13362267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com