简体   繁体   English

检查对象是否为空

[英]Checking if an object is null

I am coding a MVC 5 internet application, and I have a question in regards to checking if an object is null or not, before setting some values in the object. 我正在编写一个MVC 5 Internet应用程序,在设置对象中的某些值之前,我有一个问题要检查对象是否为空。

Here is some example code: 这是一些示例代码:

public async Task TestFunction(TestObject obj)
{
    obj.name = "Test Name";
    repository.Insert(obj);
}

Should the check to see if the object is null be done before the function call every time? 是否应该在每次函数调用之前检查对象是否为null? Is there any need at all to check if the object is null within the function call? 有没有必要检查函数调用中对象是否为null?

Thanks in advance. 提前致谢。

It depends on the purpose of the function, in your function's case it looks like you will be using it to insert the object into a repository therefore passing a null object into a repository should throw an exception and not just silently fail. 这取决于函数的用途,在函数的情况下,您似乎将使用它将对象插入到存储库中,因此将空对象传递到存储库中应该引发异常,而不仅仅是默默地失败。

You should check for null and throw an ArgumentException if the parameter is null. 如果参数为null,则应检查是否为null并引发ArgumentException

public async Task TestFunction(TestObject obj)
{
    if(obj == null) {
        throw new ArgumentException("obj cannot be null");
    }

    obj.name = "Test Name";
    repository.Insert(obj);
}

However there are cases where you could have a function that can accept a null object possibly returning a default value if you do pass it in. 但是,在某些情况下,您可能会有一个可以接受空对象的函数,如果您将其传入,则可能返回默认值。

Just don't write code like this: 只是不要写这样的代码:

public async Task TestFunction(TestObject obj)
{
    if(obj != null) {//if null don't do anything 
        obj.name = "Test Name";
        repository.Insert(obj);
    }
}

This method will do nothing and if the developer calling it didn't realise that the object passed was null then it will fail silently without letting the developer know what happened. 此方法不会执行任何操作,如果开发人员调用它时未意识到所传递的对象为null,则它将在不让开发人员知道发生了什么的情况下静默失败。

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

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