将C#中的'var'值初始化为null [英] Initialize value of 'var' in C# to null

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

问题描述

我想将变量分配给null的初始值,并在下一个 if - else 块中分配其值,但是编译器给出了错误,

I want to assign a variable to an initial value of null, and assign its value in the next if-else block, but the compiler is giving an error,

类型明确的局部变量必须初始化.

Implicitly-typed local variables must be initialized.

我怎么能做到这一点?

推荐答案

var 变量仍然具有类型-编译器错误消息指出必须在声明期间建立此类型 .

var variables still have a type - and the compiler error message says this type must be established during the declaration.

可以完成特定的请求(分配初始null值),但我不建议这样做.它在这里没有优势(因为必须仍然指定类型),并且可以被视为使代码的可读性降低:

The specific request (assigning an initial null value) can be done, but I don't recommend it. It doesn't provide an advantage here (as the type must still be specified) and it could be viewed as making the code less readable:

var x = (String)null;

仍是推断类型"的,等同于:

Which is still "type inferred" and equivalent to:

String x = null;

编译器不会接受 var x = null ,因为它不将null与任何类型相关联-甚至不与Object相关联.使用上述方法, var x =(Object)null 会起作用",尽管它的有用性令人怀疑.

The compiler will not accept var x = null because it doesn't associate the null with any type - not even Object. Using the above approach, var x = (Object)null would "work" although it is of questionable usefulness.

通常,当我不能正确使用 var 的类型推断时,

Generally, when I can't use var's type inference correctly then

  1. 我在一个最好显式声明变量的地方;或
  2. 我应该重写代码,以便在声明期间分配 valid 值(具有已建立的类型).
  1. I am at a place where it's best to declare the variable explicitly; or
  2. I should rewrite the code such that a valid value (with an established type) is assigned during the declaration.

第二种方法可以通过将代码移入方法或函数中来完成.

The second approach can be done by moving code into methods or functions.

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

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