是否将 null 传递给可接受的方法 [英] Is passing null in to a method acceptable

查看:46
本文介绍了是否将 null 传递给可接受的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Null 对我来说是一种奇怪的数据类型,似乎永远使用它是错误的,也许是我作为初学者经常遇到的空指针错误,现在让我将任何 null 实例与某种邪恶相关联!

Null is an odd data type for me, it seems as though it is wrong to ever use, maybe its the null pointer errors i got so often as a beginner that now have me associating any instance of null to some kind of evil!

无论如何我的问题是

在某些情况下可以使用 null 作为参数吗?例如,一个方法可能需要a和b来完成一个任务,但在某些情况下它可能只需要a.在那些奇怪的实例中为 b 解析 null 是否可以并检查 if(b==null) 那么我们知道它叫什么?

in some cases is it ok to use null as a parameter? for example, a method may need a and b to do a task, but in some cases it may only need a. Is parsing in null ok for b in those odd instances and checking if(b==null) then we know what called it?

或者我在这里的标记方式?

Or am i way of the mark here?

我必须承认,让我想知道这是否可以接受的是,所讨论的方法可能会过载,但在整个方法中可能会有 5 或 6 行的差异.这让我担心代码重复.

i must admit, what got me wondering whether this was acceptable was, the method in question could be overlaoded, but it would have a difference of possibly 5 or 6 lines out of the whole method. This made me worried about code duplication.

推荐答案

null 传递给方法绝对没问题.但是,如果您有可能不需要传递变量的 csae,请考虑 重载.

It is absolutely fine to pass null to methods. However, if you have a csae where you might not need to pass a variable, consider overloading.

我个人使用可选参数 - 由于方法作为合同的问题,有很多关于这个主题的讨论,其中不在此问题的范围内.

I personally would not use optional parameters - there are many discussions on this very subject because of the issue with the method as Contract which is outside the scope of this question.

正确的做法不是重复代码而是让重载相互调用:

Correct way to do it is not to duplicate code but let overloads call each other:

public void Foo(A a)
{
    Foo(a, null);
}
public void Foo(A a, B b)
{
        // .......
}

这将告诉客户端此代码:

This will tell client of this code:

  • 只能使用 A 调用方法
  • 您可以使用 A 和 B 调用方法

如果我只有第二种方法,客户端将不知道是否可以传递null.

If I have only the second method, the client would not know if it is OK to pass null.

这篇关于是否将 null 传递给可接受的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆