为什么我们不能声明var a = new List< string>在课堂上? [英] Why can't we declare var a = new List<string> at class level?

查看:40
本文介绍了为什么我们不能声明var a = new List< string>在课堂上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们不能在类级别上执行此操作,但是在方法级别上我们始终可以执行此操作.

I know we cannot do this at class level but at method level we can always do this.

var myList=new List<string> // or something else like this

这个问题浮现在我的脑海,因为无论我们在哪里声明这样的变量.我们总是在表达式的RHS处提供类型信息.因此,编译器不需要进行类型猜测.(如果我错了,请纠正我).

This question came to my mind since wherever we declare variable like this. We always provide the type information at the RHS of the expression. So compiler doesn't need to do type guessing. (correct me if i am wrong).

所以问题仍然是为什么不在类级别,而在方法级别却允许

so question remains WHY NOT at class level while its allowed at method level

推荐答案

实现此功能存在技术问题.常见的情况看似简单,但困难的情况(例如,在链或循环中引用其他字段的字段,包含匿名类型的表达式)并非如此.

There are technical issues with implementing this feature. The common cases seem simple but the tougher cases (e.g., fields referencing other fields in chains or cycles, expressions which contain anonymous types) are not.

有关详细说明,请参见Eric Lippert的博客:

See Eric Lippert's blog for an in-depth explanation: Why no var on fields?

这篇关于为什么我们不能声明var a = new List&lt; string&gt;在课堂上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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