简体   繁体   English

如何处理可能返回null并生成System.NullReferenceException的方法

[英]How to handle a method that might return null and generate a System.NullReferenceException

I have a method with the return type Fruit , that does the following: 我有一个返回类型为Fruit的方法,它执行以下操作:

Search for the right apple, if it matches return it; else
Search for the right banana, if it matches return it; else
Search for the right orange, if it matches return it; else
return null

Fruit is an interface that has the following: Fruit是一个具有以下内容的接口:

bool Rotten { get; set; }

The problem is that when I try to use it: 问题是当我尝试使用它时:

store.GeTAFruit("magic apple").Rotten;

If it does not find the fruit it will return null, and that will give a NullReferenceException . 如果找不到水果,它将返回null,这将产生NullReferenceException

Of course I can surround it with a try catch but that means that every time I use this function I will have to surround it with try catch, that doesn't seem like a good idea at all. 当然我可以用try catch来包围它,但这意味着每次我使用这个函数时我都必须用try catch包围它,这看起来根本不是一个好主意。

I'm looking either for a solution to this problem, or rather what would be the best approach for this. 我正在寻找解决这个问题的方法,或者更确切地说是最好的方法。

If GetAFruit can return null, then (and here's the technical bit): check for null : 如果GetAFruit可以返回null,那么(这里是技术位): 检查null

var fruit = store.GetAFruit(...);
if(fruit != null) {
    //... Do stuff
}

this may help 这可能有所帮助

if (store.GeTAFruit("magic apple")!=null) {
store.GeTAFruit("magic apple").Rotten;
} 

edit to make it a tiny bit more efficient: 编辑 ,使其更有效:

var fruit = store.GeTAFruit("magic apple");
if (fruit!=null)) {
    fruit.Rotten;
} 

Simply check that store.GeTAFruit("magic apple") is not null: 只需检查store.GeTAFruit("magic apple")是否为空:

   if (store.GeTAFruit("magic apple") != null) {

   }

There are two approaches if you do not want to use exception handling. 如果您不想使用异常处理,有两种方法。 But the essence of them is the same. 但它们的本质是一样的。 You must evaluate the lookup result to test it for null before using it. 在使用之前,必须评估查找结果以将其测试为null。

The first option is to assign the result of your lookup to a variable and then test if before you use it. 第一个选项是将查找结果分配给变量,然后在使用之前测试它。

Fruit fruit = store.GeTAFruit("magic apple");
if(fruit != null)
{
    //safely use your Rotten property
    bool lFlag = fruit.Rotten;
}

An alternative is to test it like so ... 另一种方法是像这样测试它......

if(store.GeTAFruit("magic apple") != null)
{
    store.GetTAFruit("magic apple").Rotten;
}

The benefits of the first approach is that you only perform the lookup once. 第一种方法的好处是您只执行一次查找。

Define a NullFruit : IFruit. 定义一个NullFruit:IFruit。 Return a instance of it if nothing is found. 如果找不到任何内容,则返回它的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM