【问题标题】:Cannot find definition though intellisense lists it?尽管智能感知列出了定义,但找不到定义?
【发布时间】: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&lt;T&gt;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&lt;int&gt;string 不是全部!!

所以如果编译器可以知道Foo 期望一个字符作为第一个参数,那么为什么我的第一个示例不直接编译呢? 换句话说,为什么在第一个示例中编译器知道 T 在这种情况下是 char?

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

"".Foo('l');

我只是想知道为什么在第一个示例中不能将T 推断为char,毕竟字符串是IEnumberable&lt;char&gt;


编辑:

我从 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&lt;T&gt;s 上可用,因为它知道 SIEnumerable&lt;T&gt;。所以我在想 C# 甚至会推断出T 的类型!谢谢大家! ;)

【问题讨论】:

    标签: c# visual-studio-2010 c#-4.0 type-inference


    【解决方案1】:

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

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

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

    【讨论】:

    • 具体设置泛型类型会起作用:"".Foo&lt;string,char&gt;();
    • @RenéWolferink 很明显,我的问题是关于为什么不自动推断类型。
    • 这就是为什么我将它添加为评论,而不是作为答案,只是为了完整性。 ;)
    • Slakhs 虽然我理解您的推理,但您发布的链接不是正确的。它谈论重载解决方案而不是类型推断。请编辑答案。
    • @nawfal:这仍然是真的,我不知道有更好的链接。
    猜你喜欢
    • 2023-04-01
    • 2014-11-25
    • 2019-01-13
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 2012-09-10
    • 2015-12-11
    • 2018-03-07
    相关资源
    最近更新 更多