为什么我必须提供明确的泛型参数类型而编译器应该推断类型? [英] Why must I provide explicitly generic parameter types While the compiler should infer the type?

查看:202
本文介绍了为什么我必须提供明确的泛型参数类型而编译器应该推断类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我必须提供明确的泛型参数类型而编译器应该推断类型?

Why must I provide explicitly generic parameter types While the compiler should infer the type?

public static T2 Cast<T1,T2>(this T1 arg) where T2 : class where T1 : class
{
    return arg as T2;
}

用法示例:

 objOfTypeT2 = objOfTypeT1.Cast<TypeT1,TypeT2>();


相比于我的一个更智能的编译器所需的用法:


Compared to my desired usage with a more intelligent compiler:

 objOfTypeT2 = objOfTypeT1.Cast<TypeT2>();

也许我应该更聪明: - )

or maybe I should be more intelligent :-)

要注意的是我公司提供的返回类型。我想不会提供我打电话就可以了函数的对象,该方法是一个扩展方法

Beware that I provide the return type. I want to not provide the object that I called the function on it, the method is an Extension Method.

推荐答案

规范限制类型参数推断通用的方法全有或全无。你不能有局部的推断。

The specification limits type parameter inference for generic methods to all or nothing. You can't have partial inference.

的理由可能是简化型推理规则(即已经pretty的复杂,因为他们必须要考虑到重载规则也是如此)。

The rationale is probably simplifying type inference rules (that are already pretty complex, as they have to take into account overloading rules too).

这篇关于为什么我必须提供明确的泛型参数类型而编译器应该推断类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆