C# - 空值检查方法

发布于 2024-10-15 06:54:36 字数 348 浏览 2 评论 0原文

检查值是否为 null 的首选方法是什么?

假设我们有一些实体,它具有属性,可以为 null (其中一些或全部)。

我希望在运行时检查此属性是否确实为 null

在这种情况下,您会使用简单的 Entity.Property != null 检查,还是会实现特定的方法,例如

bool HasProperty() {
   return Property != null;
}

您会选择什么以及为什么?

What's the preferred way of checking if the value is null?

Let's say we have some entity, which has properties, which can be null (some of them or all of them).

And I wish to check this in runtime, if some property is actually null or not.

Would you use simple Entity.Property != null check in this case or would you implement a specific method, let's say like

bool HasProperty() {
   return Property != null;
}

What would you choose and why?

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

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

发布评论

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

评论(7

盛夏已如深秋| 2024-10-22 06:54:36

对于可以为 null 的属性值,我的偏好是执行以下操作

  1. 拥有包含可能为 null 的值的属性
  2. 拥有另一个以 Has< 为前缀的属性/code> 以及包含原始属性名称的其余部分,用于确定另一个属性是否为非 null
  3. 如果在 null 时访问原始属性,则将断言添加到原始属性中

在本示例中,这将是

SomeType Property { 
  get { 
    Contract.Requires(HasProperty);
    return _property; }
}

bool HasProperty {
  get { return _property != null; }
}

背后的原因问题是 C# 没有标准方法来描述值是否可以为 null。有许多不同的约定和技术可用,但根本没有标准。不理解值周围的 null 语义会导致错过 null 检查并最终导致 NullReferenceExceptions

我发现表达这一点的最佳方法是当且仅当该属性可以时,通过添加 Has 属性,使属性的 null 特性在类型本身中显式显示。为null。这不是一个完美的解决方案,但我发现它在大型项目中效果很好。

我尝试过的其他解决方案

  1. 什么也不做:这只会一次又一次地失败
  2. 使用 F# 风格的显式 MaybeOption 类型。这是可行的,但我发现我收到了很多来自从未进行过函数式编程的开发人员的反对,这导致我完全拒绝这个想法,而完全支持#1。

For property values which can be null, my preference is to do the following

  1. Have the property containing the value which can possibly be null
  2. Have another property prefixed with Has and the rest containing the original property name which determines if the other property is non-null
  3. Add an assert into the original property if it's accessed when null

In this example it would be

SomeType Property { 
  get { 
    Contract.Requires(HasProperty);
    return _property; }
}

bool HasProperty {
  get { return _property != null; }
}

The reasoning behind this is that C# does not have a standard way of describing whether or not a value can be null. There are many different conventions and techniques avalaible but simply no standard. And not understanding the null semantics around a value leads to missed null checks and eventually NullReferenceExceptions.

I've found the best way to express this is to make the null feature of a property explicit in the type itself by adding the Has property if and only if the property can be null. It's not a perfect solution but I've found it works well in large projects.

Other solutions I've tried

  1. Do Nothing: This just fails over and over again
  2. Using an explicit Maybe<T> or Option<T> type in the flavor of F#. This works but I find I receive a lot of push-back from developers who've never done functional programming and it leads to a rejection of the idea entirely in favor of #1.
原野 2024-10-22 06:54:36

只需检查属性本身是否为 null,无需为此创建方法。属性实际上只是编译器生成的方法。

Just check if the property itself is null, there is no need to create a method for this. Properties are really just methods that are generated by the compiler.

爱你是孤单的心事 2024-10-22 06:54:36

没有任何模式可以涵盖这一点。事实上,任何试图让这个“更容易”的事情都可以被视为反模式。

“嘿,不要检查属性是否为 null,使用 Is[Property Name]Null 属性”

呃,不。

There is no pattern that covers this. In fact, anything you do to try and make this "easier" could be considered an anti-pattern.

"Hey, don't check if the property is null, use the Is[Property Name]Null property"

Uh, no.

站稳脚跟 2024-10-22 06:54:36

我仅检查 null,因为每个可为 null 的类型在内部都完全按照您所描述的方式执行操作(但内部方法称为 HasValue 而不是 HasProperty):

http://msdn.microsoft.com/de-de/library/b3h38hb0.aspx

I check only against null, because every nullable type does internally exactly what you described (but the internal method is called HasValue instead of HasProperty):

http://msdn.microsoft.com/de-de/library/b3h38hb0.aspx

梦归所梦 2024-10-22 06:54:36

如果 Property 不是公共的,那么您将需要像 HasProperty() 这样的方法。另外,如果您以另一种方式实现“空性”,那么拥有 HasProperty() 方法也很好。

If Property is something that isn't public, then you would need a method like HasProperty(). Also, if you implement your "nullness" in another way, it would also be good to have a HasProperty() method.

独木成林 2024-10-22 06:54:36

空不一定是坏事。我认为这完全取决于为什么您需要检查 null 以确定如何您应该检查它。

Null is not necessarily bad. I think it all depends on why you need to check for null to determine how you should check for it.

淡看悲欢离合 2024-10-22 06:54:36

仅当该属性自动初始化时(即仅获取它可能会导致分配一个空集合)并且它会产生性能差异,我才会选择编写单独的 Has* 属性。如果获取该属性的成本很便宜(理应如此;但在某些情况下,您只是情不自禁地让它发挥作用),则不需要多余的 Has 方法。

所以对于一般情况没有:

public string Foo { get; set; }

但在某些情况下,这可能是一个好主意:

private List<string> someStrings = null;

public List<string> SomeStrings {
    get {
        if (someStrings == null)
            someStrings = new List<string>();
        return someStrings;
    }
}

public bool HasSomeStrings {
    get { return (someStrings != null && someStrings.Count > 0); }
}

I would choose to write a separate Has* property only if the property is auto-initializing (i.e. just getting it might cause, say, an empty collection to be allocated) and it makes a performance difference. If getting the property is cheap (as it should be; in some cases you just can't help having it make a difference, though), there's no need for a superfluous Has method.

So no Has for the general case:

public string Foo { get; set; }

But in some cases, it can be a good idea:

private List<string> someStrings = null;

public List<string> SomeStrings {
    get {
        if (someStrings == null)
            someStrings = new List<string>();
        return someStrings;
    }
}

public bool HasSomeStrings {
    get { return (someStrings != null && someStrings.Count > 0); }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文