加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C#编译器如何解释var关键字指定的对象?

发布时间:2020-12-16 00:12:56 所属栏目:百科 来源:网络整理
导读:C#编译器如何解释var关键字指定的对象?我们何时必须使用此关键字? 解决方法 在Var声明中, Compiler infer the type from the assigned value 上 var a = 100; // compiler assumes a is a integervar b = "test"; // compiler assumes b is a string 为什
C#编译器如何解释var关键字指定的对象?我们何时必须使用此关键字?

解决方法

在Var声明中,

Compiler infer the type from the
assigned value

var a = 100;     // compiler assumes a is a integer
var b = "test";  // compiler assumes b is a string

为什么我们需要它们(为什么我们不能直接使用对象)

因为对象不强制类型安全

object objtest = 1;
  objtest = "test";

这很好用.

但var强制类型安全

var a = 100;    
  a= "test";

这不编译,并将给出编译时错误.

我们可以在哪里使用它们

> Linq查询返回匿名类型
>以及您想要定义类型安全变量的任何地方(简单).而不是写作
这样的事情.

.

RootClass rt = new RootClass ();
   List<RootClass > rt = new List<RootClass >();

你可以写这样的

var aaaaaa = new RootClass ();
var ls = new List<RootClass>();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读