c#值为null怎么解决
Null Reference Exception is one of the most occurring exception. Object oriented languages generally creates new object for the variables. But if it is not created and not set by the developer trying to access an variable object will cause Null Reference Exception. In this examples we will use Csharp programming language for Null Reference Exception.
空引用异常是最常发生的异常之一。 面向对象的语言通常会为变量创建新的对象。 但是,如果未创建它并且开发者未设置它试图访问变量对象,则将导致Null Reference Exception。 在此示例中,我们将为空引用异常使用Csharp编程语言。
引发Null参考异常 (Raise Null Reference Exception)
We can generate Null Reference Exception with the following example code. In this code we create a variable named name
and set its value t null. If we try to run function ToUpper()
which will return the name
variable string in uppercase will create an Exception because there is no such value to use.
我们可以使用以下示例代码生成Null Reference Exception。 在此代码中,我们创建一个名为name
的变量并将其值设置为null。 如果我们尝试运行函数ToUpper()
,该函数将以大写形式返回name
变量字符串,则会创建一个Exception,因为没有可使用的此类值。
string name=null;
name.ToUpper();
Another example can be a class or struct which is not set into an instance. This example will be similar to the previous example. We will create a variable ferrari
which is a Car
class type.
另一个示例可以是未设置为实例的类或结构。 此示例将类似于前面的示例。 我们将创建一个可变的ferrari
,它是Car
类类型。
Car ferrari;
ferrari.Start();
解决Null参考异常 (Solve Null Reference Exception)
This code snippet will cause Null Reference Exception. To remove Null Reference Exception initialize the name object. We simply set some value different than null to prevent Null Reference Exception.
此代码段将导致Null引用异常。 要删除Null引用异常,请初始化名称对象。 我们只是简单地设置一些不同于null的值来防止Null Reference Exception。
string name="This will not throw Null Reference Exception";
name.ToUpper();
翻译自: https://www.poftut.com/c-sharp-programming-language-null-reference-exception-and-solution/
c#值为null怎么解决