&是什么QUOT; VAR"在C#是什么意思? [英] What does "var" mean in C#?

查看:135
本文介绍了&是什么QUOT; VAR"在C#是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,如何做无功的工作????

In C#, how does "var" work????

推荐答案

这意味着,宣布当地存在的类型将被编译器推断出:

It means that the type of the local being declared will be inferred by the compiler:

// This statement:
var foo = "bar";
// Is equivalent to this statement:
string foo = "bar";

值得注意的是, VAR 不定义一个变量是一个动态的类型。因此,这是不合法的:

Notably, var does not define a variable to be of a dynamic type. So this is NOT legal:

var foo = "bar";
foo = 1; // Compiler error, the foo variable holds strings, not ints

VAR 只有两个用途:


  1. 它需要较少的打字声明变量,变量声明为嵌套泛型类型时尤其如此。

  2. 必须存储到一个匿名类型的对象的引用时使用,因为类型名称不能预先知道:无功富=新{吧=酒吧};

  1. It requires less typing to declare variables, especially when declaring a variable as a nested generic type.
  2. It must be used when storing a reference to an object of an anonymous type, because the type name cannot be known in advance: var foo = new { Bar = "bar" };

您不能使用 VAR 作为任何东西,但当地人的类型。所以你不能使用关键字 VAR 申报字段/属性/参数/返回类型。

You cannot use var as the type of anything but locals. So you can't use the keyword var to declare field/property/parameter/return types.

这篇关于&是什么QUOT; VAR"在C#是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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