c#值为null怎么解决_C#编程语言Null参考异常和解决方案

c#值为null怎么解决

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();
LEARN MORE  C Printf() Function Tutorial with Examples
了解更多C Printf()函数教程,并提供示例

翻译自: https://www.poftut.com/c-sharp-programming-language-null-reference-exception-and-solution/

c#值为null怎么解决

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值