Son*_*nül 0 c# variables types var reference
这可能是一个愚蠢的问题,但我真的不知道原因.
// i is compiled as an int
var i = 5;
// s is compiled as a string
var s = "Hello";
// a is compiled as int[]
var a = new[] { 0, 1, 2 };
// expr is compiled as IEnumerable<Customer>
// or perhaps IQueryable<Customer>
var expr =
from c in customers
where c.City == "London"
select c;
// anon is compiled as an anonymous type
var anon = new { Name = "Terry", Age = 34 };
// list is compiled as List<int>
var list = new List<int>();
Run Code Online (Sandbox Code Playgroud)
如果是这样,为什么C#需要积分类型,如int,string,int[],List<>?如果我们只能用var关键字做到这一点,为什么有整体类型?
其他方式,
这些有什么区别?
var s = "Hello";
string s = "Hello";
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 12
没有特别的顺序......
var只是一个编译器构造; 甚至var i = 4;打字为intvar,如果不破坏现有代码,就无法删除关键字.int代替var!特别是当类型很重要并且有字节,浮点数,枚举,小数等等都与文字一起使用时0; 即short x = 0; int y = 0; long z = 0;-为什么要改变只 int到var那里?var用来指定泛型类型参数(<T>)或在typeofvar.TryParse代替int.TryParse许多人会认为写作int i = 5而不是写作是更好的做法var i = 5.造成这种情况的原因有很多,但对我来说最引人注目的是我可以查看代码并立即知道,而不是拉伸我的大脑,是什么类型i.这使我的大脑能够专注于更难的问题.
事实上,它var被引入来声明其类型无法轻易命名的变量.虽然它可以这样使用,但它并不是为了方便而引入的.