如何判断一个变量是否已在 C# 中初始化?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1195597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:33:38  来源:igfitidea点击:

How to tell whether a variable has been initialized in C#?

c#classissetnothing

提问by niklasfi

I know this is a dumb question and I guess it must have been asked before. However I am unable to find an answer to my question.

我知道这是一个愚蠢的问题,我想以前肯定有人问过。但是,我无法找到我的问题的答案。

Here is some sample code (which of course does not compile) to outline my problem:

这是一些示例代码(当然不能编译)来概述我的问题:

class test
{
     int[] val1;
     string val2;

     static bool somefunction(test x, test y)
     {
         dosomestuff()

         test result;

         while(result is nothing)
         {
              if(somecondition){result=new test(something);}
         }
     }
}

The problem which I have is in the following line:

我遇到的问题在以下几行:

while(result is nothing)

This is the syntax from VB, which of course is not what the C# compiler accepts. Could somebody tell me how to resolve the problem?

这是来自 VB 的语法,这当然不是 C# 编译器所接受的。有人能告诉我如何解决这个问题吗?

采纳答案by Colin Mackay

The syntax you are looking for is:

您正在寻找的语法是:

while (result == null)

You also have to set result = null;to start with also

您还必须设置result = null;以也开始

回答by Robert Harvey

while (result == null)

回答by satyajit

while (result ==null )

if that's what you mean

如果这就是你的意思

回答by Supertux

while(result == null)

The equivalent of nothing in C# is null.

相当于 C# 中的 nothing 为 null。

回答by djangofan

while (result == null)

回答by Daniel Earwicker

Although you have an answer you're happy with, there's something behind this you may find interesting or helpful.

尽管您有一个满意的答案,但您可能会发现这背后有一些有趣或有用的东西。

There is a difference between C# and VB.NET. In VB.NET you can write:

C# 和 VB.NET 之间存在差异。在 VB.NET 中,您可以编写:

Dim b as Boolean

And in C# you can write:

在 C# 中,您可以编写:

bool b;

They are subtly different. In VB.NET, bhas been given the value false (in other words, it has already been initialized). In C#, bhas no value (it is uninitialized). C# goes to a lot of effort to make sure you cannot examine the value of a variable that has never been initialized.

他们有微妙的不同。在 VB.NET 中,b已被赋予值 false(换句话说,它已被初始化)。在 C# 中,b没有值(未初始化)。C# 付出了很多努力来确保您无法检查从未初始化的变量的值。

So you are not testing whether the variable is initialized. In VB.NET there is no such thing as an uninitialized variable. In C# it is impossible to get the value of an uninitialized variable in order to compare it with anything.

因此,您不是在测试变量是否已初始化。在 VB.NET 中,没有未初始化的变量这样的东西。在 C# 中,无法获取未初始化变量的值以将其与任何内容进行比较。

You're testing whether the variable has been initialized to nullor Nothing.

您正在测试变量是否已初始化为nullNothing

回答by Aaron Thoma

  • TL;DR:

    if (Object.Equals(myVariable, default(MyVariableType)))

    • Replace myVariableand MyVariableType.


    There are other solutions.

  • 特尔;博士:

    if (Object.Equals(myVariable, default(MyVariableType)))

    • 替换myVariableMyVariableType


    还有其他解决方案。



if (myVariable == null)will not work[1]with valuetypes. The value types mainly are structs (e.g. DateTime), including[2]the simple typeslike int, and enumerations. Value types don't support a nullvalue (intrinsically).

if (myVariable == null)不起作用[1]类型。值类型主要是structS(例如DateTime),其中包括[2]简单类型int,和enum操作。值类型不支持null值(本质上)。

The exception and the fix to this are nullabletypes: Essentially these add nullto the possible values of a struct type. They are structurally the same as the Maybe<T>you might know from other languages[3]. You create them with ValueType?(e.g. int?) which is syntactic sugar for Nullable<ValueType>.

异常和修复是可空类型:本质上这些添加null到结构类型的可能值。它们在结构上与Maybe<T>您可能从其他语言中了解到的相同[3]。你用ValueType?(eg int?)创建它们,这是Nullable<ValueType>.


Alternatively, instead of using a nullable type, you could compare your variable to its type's default value:


或者,您可以将变量与其类型的默认值进行比较,而不是使用可空类型:

if (Object.Equals(myVariable, default(MyVariableType)))

(This will work both for reference types (objects) and value types.)
Note that you have to replace MyVariableTypemanually – unfortunately you can notdo

(这对引用类型(对象)和值类型都适用。)
请注意,您必须MyVariableType手动替换- 不幸的是,您不能这样做

if (Object.Equals(myVariable, default(myVariable.GetType())))

because default()only accepts a type name directly. (I suppose it evaluates at compile-time.)

因为default()只直接接受类型名称。(我想它在编译时评估。)



structsin a nutshell

结构简而言之

Put simply, structs are cut-down classes. Imagine classes that don't support inheritance or finalizers, and you have the cut-down version: the struct. Structs are defined in the same way as classes (except with the structkeyword), and apart from the limitations just described, structs can have the same rich members, including fields, methods, properties and operators.
[Cited from: http://www.albahari.com/valuevsreftypes.aspx]

简而言之,结构是精简的类。想象一下不支持继承或终结器的类,你有一个精简的版本:结构。结构体的定义方式与类相同(除了有struct关键字),除了刚刚描述的限制外,结构体可以具有相同的丰富成员,包括字段、方法、属性和运算符。
[引自:http: //www.albahari.com/valuevsreftypes.aspx]

Classes are reference types: A class variable (or more specifically, its memory area) only contains a pointer to an other memory area, where the actual object instance data is stored.

类是引用类型:一个类变量(或者更具体地说,它的内存区域)只包含一个指向其他内存区域的指针,其中存储了实际的对象实例数据。

Value typevariables directly contain the data. This may yield a speed benefit due to cache localityand saving the lookup. But it may also be detrimental to performance in the case of more complex structs.

值类型变量直接包含数据。由于缓存位置和保存查找,这可能会产生速度优势。但在结构更复杂的情况下,它也可能对性能不利。





Footnotes:

脚注:

[1] It does not even throw an error. myVariable == nullwill always just yield false, because your myVariablewill be initialized with the non-nulldefaultvalue (zero (equivalent) or a struct of zeros and nulls). This default value is available with default(Type).

[1] 它甚至不会抛出错误。myVariable == null将始终只是 yield false,因为您myVariable将使用非null默认值(零(等效)或零和nulls的结构)进行初始化。此默认值可用于default(Type).

[2] Technically the simple types (all built-in typesexcept stringand object) arestructs. Side note: The built-in types are aliasesfor types from the Systemnamespace.

[2] 从技术上讲,简单类型(除and之外的所有内置类型都是结构体。附注:内置类型的别名从类型的系统命名空间。stringobject

[3] E.g. in Haskell. In C# Maybe<T>is not built-in, but can be implemented. It provides Nothingas a more explicit/self-documenting version of nullboth for classes and structs.

[3] 例如在 Haskell 中。在 C#Maybe<T>中不是内置的,但可以实现。它为类和结构提供Nothing了更明确/自文档化的版本null

[4] There is no [4]. No really, you can go and check.

[4] 没有[4]。真的没有,你可以去看看。