是否返回类型的C#支持类型推断? [英] Does C# support type inference of the return type?

查看:128
本文介绍了是否返回类型的C#支持类型推断?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这只是好奇一下,如果没有停止这样的一个根本的东西(或纠正我,如果有已经有一些方式):

 公共TTO转换< TTO,TFrom>(从TFrom)
{

}

这样调用:

  SOMETYPE SOMETYPE = converter.Convert(someOtherType); 


解决方案

因为如果你这样做会发生什么?

 静态无效M(INT X){} 
静态无效M(双X){}
静态Ť N'LT; T>(){}

M(N());

现在什么为T? int或double?



这一切都非常容易,当你知道你分配给什么样的类型来解决这个问题的的,但大部分当时的您指定的类型是你想在第一时间的弄清楚的东西。



推理从内到外是够硬。推理从外到内困难得多,而在同一时间做这两个是非常困难的。如果它是很难的的编译的理解正在发生的事情,想象它是多么困难的人试图阅读,理解和调试时,推论可以做成两个中的代码的表达式的上下文的类型。这种推论使得节目更难的理解,不是的更容易的,所以这将是一个糟糕的主意,将其添加到C#。



现在,这么说,C#的的支持与lambda表达式此功能。当面对一个重载的问题,其中的lambda可以绑定两个,三个或一百万的方式不同,我们将其绑定两个,三个或一百万个不同的方式,然后评估这些万种不同的可能的绑定以确定哪一个是最好的。这使得重载至少NP-HARD在C#中,我花了一年的大部分时间来实现。我们愿意使该投资,因为(1)的lambda是真棒,和(2)的大部分人编写程序的时间,可以在合理的时间量进行分析,并且可以被人类理解。所以这是值得的成本。但总的来说,那种先进的分析是不值得的代价。


This is just a curiousity about if there is a fundamental thing stopping something like this (or correct me if there's already some way):

public TTo Convert<TTo, TFrom>(TFrom from)
{
    ...
}

Called like this:

SomeType someType = converter.Convert(someOtherType);

解决方案

Because what would happen if you did this?

static void M(int x){}
static void M(double x){}
static T N<T>() {}
...
M(N());

Now what is T? int or double?

It's all very easy to solve the problem when you know what the type you're assigning to is, but much of the time the type you're assigning to is the thing you're trying to figure out in the first place.

Reasoning from inside to outside is hard enough. Reasoning from outside to inside is far more difficult, and doing both at the same time is extremely difficult. If it is hard for the compiler to understand what is going on, imagine how hard it is for the human trying to read, understand and debug the code when inferences can be made both from and to the type of the context of an expression. This kind of inference makes programs harder to understand, not easier, and so it would be a bad idea to add it to C#.

Now, that said, C# does support this feature with lambda expressions. When faced with an overload resolution problem in which the lambda can be bound two, three, or a million different ways, we bind it two, three or a million different ways and then evaluate those million different possible bindings to determine which one is "the best". This makes overload resolution at least NP-HARD in C#, and it took me the better part of a year to implement. We were willing to make that investment because (1) lambdas are awesome, and (2) most of the time people write programs that can be analyzed in a reasonable amount of time and can be understood by humans. So it was worth the cost. But in general, that kind of advanced analysis is not worth the cost.

这篇关于是否返回类型的C#支持类型推断?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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