检查构造函数中是否为 Null

发布于 2024-10-13 17:48:51 字数 330 浏览 2 评论 0原文

我真的很想找出易于调试的可重用代码的最佳实践。我遇到了开发人员中的一个常见做法,但我还不太理解。

public MyConstructor(Object myObject)
{
    if (myObject == null)
        throw new ArgumentNullException("myObject is null.");
    _myObject = myObject;
}

似乎没有必要进行这项检查。但我认为这是因为我不完全理解做这个检查的好处是什么。似乎无论如何都会抛出空引用异常?我可能错了,真的很想听听一些想法。

谢谢。

I'm really trying to figure out the best practices for reusable code that is easily debugged. I have ran into a common practice among developers that I don't quite understand yet.

public MyConstructor(Object myObject)
{
    if (myObject == null)
        throw new ArgumentNullException("myObject is null.");
    _myObject = myObject;
}

It almost seems unnecessary to do this check. But I think it's because I don't completely understand what the benefits of doing this check are. It seems like a null reference exception would be thrown anyway? I am probably wrong, would really like to hear some thoughts on it.

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

乱世争霸 2024-10-20 17:48:51

对于编译器来说,null 是合法的构造函数参数。

您的类可能能够处理 myObject 的空值。但如果不能 - 如果您的类在 myObject 为 null 时会中断 - 那么检查构造函数可以让您 快速失败

To the compiler, null is a legitimate constructor argument.

Your class might be able to handle a null value for myObject. But if it can't - if your class will break when myObject is null - then checking in the constructor allows you to fail fast.

倦话 2024-10-20 17:48:51

其他人已经正确地指出,null 参数的传递可能有效也可能无效,具体取决于使用代码的功能。

如果不需要 null 参数,从 C# 7.0 开始,可以使用抛出表达式,它允许我们更简洁地重写 null 检查代码如以下示例所示:

public MyConstructor(Object myObject)
{
    _myObject = myObject ?? throw new ArgumentNullException(nameof(myObject));
}

上面会将 _myObject 的值设置为参数 myObject 除非该参数为 null,在这种情况下,将抛出ArgumentNullException

Others have already correctly stated that the passing of a null parameter may or may not be valid depending upon the functionality of the consuming code.

Where a null parameter is undesirable it is possible, from C# 7.0, to use throw expressions which allow us to rewrite null checking code much more succinctly as the following example shows:

public MyConstructor(Object myObject)
{
    _myObject = myObject ?? throw new ArgumentNullException(nameof(myObject));
}

The above will set the value of _myObject to the parameter myObject unless that parameter is null, in which case an ArgumentNullException will be thrown.

无悔心 2024-10-20 17:48:51

在许多情况下,传递 null 对象是完全合法的 - 对于此类,实现者希望确保您无法在不传递有效 Object 实例的情况下创建该类的实例不过,所以以后不必进行检查 - 尽早确保这一点是一个很好的做法,这将在构造函数中进行。

Passing a null object is perfectly legal in many cases - for this class the implementor wants to ensure that you cannot create an instance of the class w/o passing a valid Object instance though, so there have to be no checks later on - it's a good practice to ensure this as early as possible, which would be in the constructor.

陌生 2024-10-20 17:48:51

如果您使用的是 4.0,您可以执行以下操作:

 public ctor(IEnjection ninjaWeapon) 
 {
     Contract.Requires<ArgumentNullException>(ninjaWeapon != null);
     this.deadlyWeaponary.Add(ninjaWeapon);
 }

如果您使用的是旧版本,请参考 Microsoft.Contract 执行相同的操作。

if you under 4.0 you can do the following:

 public ctor(IEnjection ninjaWeapon) 
 {
     Contract.Requires<ArgumentNullException>(ninjaWeapon != null);
     this.deadlyWeaponary.Add(ninjaWeapon);
 }

if you under an older version, reference the Microsoft.Contract to do the same thing.

冷了相思 2024-10-20 17:48:51

编译器不知道对象的值,因此您必须在运行时检查它以确保不会使用空值调用它。

这还取决于您的特定解决方案。你不需要抛出异常,只有当你不能让该值为空时我才会抛出它,如果它为空,那就是一个例外情况。

The compilier has no idea about the value of an object, so you have to check this at runtime to ensure it doesn't get called with a null value.

It also depends on your particular solution. You don't need to throw the exception, I would only throw it if you can not have that value be null, and if it is null, that is an exceptional case.

谁把谁当真 2024-10-20 17:48:51

我认为一般不可能判断是否有必要检查 null 。这取决于您是否可以接受空值变量。 Null 本身并不是一个坏状态。您可能会遇到允许变量为空而不允许变量为空的情况。

问问自己允许空值是否有意义,并相应地设计构造函数。

I think that it is not possible to tell generally whether checking for null is necessary or not. It rather depends on whether you can live with null valued variables or not. Null is not per se a bad state. You might have situations where it is allowed for a variable to be null and other where it is not.

Ask yourself whether it makes sense to allow null values or not and design the constructor accordingly.

む无字情书 2024-10-20 17:48:51

您可以实现一个简单的 ThrowIfNull 扩展方法来减少每次编写的代码。 Jon Skeet 在他的 博客 以及此处引用的 SO 文章。

You could implement a simple ThrowIfNull extension method to reduce the code you write each time. Jon Skeet covered this in his blog and the referenced SO article here.

○愚か者の日 2024-10-20 17:48:51

您需要显式检查 null ,因为编译器不知道,而且还因为 null 可以是有效参数。

You need to explicitly check for null because the compiler doesn't know, but also because null can be a valid argument.

小…红帽 2024-10-20 17:48:51

好处是异常会在对象构造时抛出,因此您可以轻松追踪哪部分代码是罪魁祸首。如果您的代码需要非空的 myobject 值,并且您没有在构造函数中验证它,则当您使用 myObject_ 时,将会抛出 NullReferenceException并且您将必须手动回溯以查看是谁发送了该空值。

The benefit is that the exception will be thrown at the time of object construction, so you can easily trace which part of code is the culprit. If your code requires non-null myobject value and you don't validate it in the constructor, the NullReferenceException will be thrown when you use myObject_ and you will have to trace back manually to see who sent that null value in.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文