在C#2.0中使用关键字var bad? [英] Is using the keyword var bad in C# 2.0?

查看:118
本文介绍了在C#2.0中使用关键字var bad?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我阅读了关于使用C#2中的C#3功能,例如可以输入 var x = 2; 即使项目是2.0项目,Visual Studio 2008编译器也会选择它并生成与输入 int x = 2 时相同的代码。 p>

但我没有得到的是,你应该不是在某些情况下这样做吗?我一直认为 var 关键字没有到达,直到C#3 ..如果编译器生成相同的代码,我可以键入C#3代码和C#2代码完全相同



b


在后台,编译器生成常规的.NET 2.0代码。


.NET 2.0代码和.NET 3代码之间有什么区别吗?

解决方案

恐怕你混淆了C#版本和.NET版本。



在C#2.0中不能使用 var ,编译器会认为它只是一个标识符。但是你可以在C#3.0针对.NET 2.0中使用它,因为 var 只是一个语言(C#)结构,而不是.NET结构。 .NET编译器会将其转换为生成的CIL中的相应类型,因此JIT编译器将永远不会看到它,您将会完全正常。



由于VS2008编译器是一个C#3.0编译器,你将没有问题使用 var 在那里,无论你的目标.NET版本。


I read an article about using C# 3 features in C# 2 where you can for instance type var x = 2; and even if the project is a 2.0 project, the Visual Studio 2008 compiler picks it up and generates the same code as it would if you type int x = 2.

But what I don't get is, should you not do this in some cases? I always thought that the var keyword didn't arrive until C# 3.. If the compiler generates the same code and I can type C# 3 code and C# 2 code exactly the same, what is the differance really, because the CLI is the same, right?

Quote from the link above

Behind the scenes, the compiler generate regular .NET 2.0 code.

Is there any difference between .NET 2.0 code and .NET 3 code?

解决方案

I am afraid you are mixing up C# versions and .NET versions.

You cannot use var in C# 2.0, the compiler will think it is just an identifier. But you can use it in C# 3.0 targeting .NET 2.0, since var is just a language (C#) construct, not a .NET construct. The .NET compiler will translate it into the appropriate type in the generated CIL, so the JIT compiler will never see it and you will be completely fine.

Since the VS2008 compiler is a C# 3.0 compiler, you will have no problem using var there, regardless of the .NET version you are targeting.

这篇关于在C#2.0中使用关键字var bad?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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