加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么C#编译器不能为返回值推断类型参数?

发布时间:2020-12-15 03:52:26 所属栏目:百科 来源:网络整理
导读:我有这个代码(为了清楚起见,最小化): interface IEitherout TL,out TR {}class LeftTL,TR : IEitherTL,TR { public Left(TL value) { }}static class Either { public static IEitherTL,TR LeftTL,TR (this TL left) { return new LeftTL,TR (left); }} 为
我有这个代码(为了清楚起见,最小化):
interface IEither<out TL,out TR> {
}

class Left<TL,TR> : IEither<TL,TR> {
    public Left(TL value) { }
}

static class Either {
    public static IEither<TL,TR> Left<TL,TR> (this TL left) {
        return new Left<TL,TR> (left);
    }
}

为什么我不能说:

static class Foo
{
    public static IEither<string,int> Bar ()
    {
        //return "Hello".Left (); // Doesn't compile
        return "Hello".Left<string,int> (); // Compiles
    }
}

我收到一个错误,指出’string’不包含’Left’的定义,并且没有扩展方法’Left’接受’string’类型的第一个参数可以被找到(你缺少using指令或程序集引用吗? (CS1061).

解决方法

我建议您看看C#规范中的7.5.2节.

7.5.2 Type inference

When a generic method is called without specifying type arguments,a
type inference process attempts to infer type arguments for the call.
The presence of type inference allows a more convenient syntax to be
used for calling a generic method,and allows the programmer to avoid
specifying redundant type information.

[…]

Type inference occurs as part of the binding-time processing of a method invocation (§7.6.5.1) and takes place before the overload resolution step of the invocation […]

那么在任何类型的重载分辨率完成之前,分辨率就会发生,问题在于推断出你所说的类型甚至没有被尝试,而且坦白地说也不总是可能的.

通用类型的参数的类型解析只能通过调用中的参数完成!在你的例子中只有一个字符串!它不能从参数中推断出int,只能在通用类型解析时解析的调用上下文.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读