如何在C#中初始化var变量 [英] How to initialize var variable in C#

查看:2018
本文介绍了如何在C#中初始化var变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在c#中初始化var varible。在该变量中我存储了值列表。



我尝试过:



我在谷歌尝试但在分配价值时收到错误。



代码添加评论

  var 结果; 
if true
results =(来自 table_name 选择 a).ToList();
else
results =( from b in table_name 选择 b).ToList();



[/ Edit]

解决方案

你不能这样做:var变量的声明必须包含系统识别数据类型所需的信息。 var ion C不是动态声明,它是固定类型的快捷方式声明,允许引用匿名类型的变量。根据运行时条件的值,您的代码可以允许变量类型动态声明为a的类型或b的类型。

C#将不允许:必须在编译时知道var变量的类型。


如果要使用 var ,则必须为声明中的变量。

例如

  var  o =  new  myObject(); 



如果你不这样做那么你必须使用明确的声明

 myObject o; 
...
o = GetmyObject();


如前所述,当使用汽车时,必须在声明点。



假设两个列表返回相同的对象类型,最容易解决问题的方法是写:

  var  results = condition? 
来自 table_name 选择 a)。ToList():
来自 b in table_name 选择 b).ToList();





否则,如果你想要类似于你的代码,然后声明变量类型:

 List< TableRowType>结果


I have to initilize var varible in c#. in that variable i stored list of values.

What I have tried:

I tried in google but getting error while assigning value.

[Edit] Code added from comment

var results;
if (true)
   results = (from a in table_name select a).ToList();
else
   results = (from b in table_name select b).ToList();


[/Edit]

解决方案

You can't do it like that: the declaration of the var variable has to include the information that the system requires to recognise the datatype. var ion C is not a dynamic declaration, it's a shortcut declaration to a fixed type which allows for variables referencing anonymous types. Your code could allow the variable type to be dynamically declared as "type of a" or "type of b" according to the value of the condition at run time.
C# won't allow that: the type of a var variable must be known at compile time.


If you are going to use var then you must assign a value to the variable in the declaration.
E.g.

var o = new myObject();


If you do not do that then you must use the explicit declaration

myObject o;
...
o = GetmyObject();


As other mentionned, when car is used, its type must be known at the point of declaration.

The easiest way to fix you problem assuming that both lists returns same object type would be to write:

var results = condition ?
   (from a in table_name select a).ToList() :
   (from b in table_name select b).ToList();



Otherwise, if you want code similar to yours, then declare the variable type:

List<TableRowType> results;


这篇关于如何在C#中初始化var变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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