-1

i have some confusing about var and not var initialization.

var x=10;

x=12;

what is the difference between those initialization in C# ?

i knew var is keyword is used for following kind of ways.

When the type is complex to write, such as a LINQ query (the reason for var in the first place) use var.

Thanks,

Siva

4

6 回答 6

1

要使用var关键字,必须有一个在等号 (=) 右侧拥有类型的表达式才能编译。

var myNumber = 1;将起作用,因为 var 将被编译为 int 作为类型。 myNumber = 1将不起作用,因为 myNumber 未声明。如果要声明等号右侧没有任何内容的变量,则必须显式指定类型,即int myNumber.

就个人而言,我只会在 var 很明显会编译成什么时才使用它......例如

var myNumber = 1; 
var name = "some name"; 
var lst = List<int>();

不太明显……

var data = GetData();

当然,你可以去方法看看返回是什么,但是对于其他开发人员来说可能更难阅读。

于 2013-08-31T13:21:20.387 回答
1

This one compiles.

var x=10;

This one does not assuming you are trying to initialize x in this scenario.

x=12;

It has to be:

int x = 12;

Now what is the difference between var x=12; and int x = 12; nothing. They are both resolved at compile time.

于 2013-08-31T13:16:34.773 回答
1

The first one is used to declare and assign a local variable x. The new variable declared will automatically get the (strong and non-dynamic) type of the right-hand side of the =. That is type int in your example.

The second one is used to assign (only) to a variable or property that has been declared already elsewhere.

于 2013-08-31T13:16:54.633 回答
0

变量

它是在 C# 3.0 中引入的

 1 ) var declarations are resolved at compile-time.
 2) Errors are caught at compile time.

当你不知道你在处理什么类型时,最好使用var它从定义它的赋值的右侧获取它。

  var x =10;

  x=12; 

在第一种情况下,编译器在运行时解析声明

让我们假设如果你会做

  var x=10;

  x="I am String";

将抛出错误,因为编译器已经确定类型x是 System.Int32 当值 10 分配给它时。现在给它分配一个字符串值违反了类型安全

优点

var当你将它与 c# 3 匿名类型和泛型结合使用时会派上用场,匿名类型仍然是 clr 类型,但在编码时你不能拥有类型名称

但是最好使用命名约定以获得更好的可读性

于 2013-08-31T13:18:21.137 回答
0
var x = 10; 

相当于

int x = 10;

var是优秀的语法糖。

当你写的时候x = 10,你x必须在之前声明。

于 2013-08-31T13:17:28.810 回答
0

var为 C# 中的任何类型起别名,其类型将由 C# 编译器确定,或者它是隐式类型的。

但在

x = 12;

你必须明确地确定类型,例如写:

int x= 12;

使用var没有性能考虑,可以自由使用。

于 2013-08-31T13:28:03.090 回答