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

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

问题描述

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

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.

基本原理可能是简化类型推断规则(这些规则已经非常复杂,因为它们也必须考虑重载规则).

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天全站免登陆