简体   繁体   English

在C#中使用可空类型

[英]Using nullable types in C#

I'm just interested in people's opinions. 我只是对人们的意见感兴趣。 When using nullable types in C# what is the best practice way to test for null: 在C#中使用可空类型时,测试null的最佳实践方法是什么:

bool isNull = (i == null);

or 要么

bool isNull = !i.HasValue;

Also when assigning to a non-null type is this: 同样,当分配给非null类型时:

long? i = 1;
long j = (long)i;

better than: 优于:

long? i = 1;
long j = i.Value;

I would use this: 我会用这个:

long? i = 1;
...some code...
long j = i ?? 0;

That means, if i is null , than 0 will be assigned. 这意味着,如果inull ,则将分配0。

Use the forms that were specially implemented for you by the C# team. 使用C#团队专门为您实现的表单。 If anyone objects, tell them Anders said it was okay. 如果有人反对,告诉他们安德斯说没关系。

What I'm saying, flippantly, is that a lot of work went into integrating nullable types into c# to give you a good programming experience. 我轻蔑地说,很多工作都是将可空类型集成到c#中,以便为您提供良好的编程体验。

Note that in terms of performance, both forms compile down to the same IL, ie: 请注意,就性能而言,两种形式都会编译为相同的IL,即:

int? i = 1;
bool isINull = i == null;
int j = (int)i;

Ends up like this after the C# compiler has got to it: 在C#编译器完成之后,这样结束:

int? i = 1;
bool isINull = !i.HasValue;
int j = i.Value;

I would always use the (i==null) form. 我总是使用(i == null)表单。 It expresses what you are doing. 它表达了你在做什么。

WRT the second question, I think either form is fine. WRT第二个问题,我认为任何一种形式都没问题。 However I'd always check it against null first and take appropriate action - perhaps wrapping that check and action up in a helper method (often it just sets a default value). 但是我总是首先检查它是否为null并采取适当的操作 - 可能在辅助方法中包装该检查和操作(通常它只是设置一个默认值)。

I haven't used Nullable Types in practice, but for the second, I'd actually suggest using j.GetValueOrDefault(). 我没有在实践中使用Nullable Types,但是对于第二种,我实际上建议使用j.GetValueOrDefault()。 The documentation suggests that the latter would actually throw an InvalidOperationException in the event of a null value. 文档表明后者实际上会在null值的情况下抛出InvalidOperationException。 Depending on the internal implementation of the explict cast operator for long?, the former might, too. 取决于explict强制转换操作符的内部实现,前者可能也是如此。 I'd stick with GetValueOrDefault and treat the null/default case appropriately. 我坚持使用GetValueOrDefault并适当地处理null / default情况。

我倾向于使用第一个,因为它需要在其生命周期的后期得到支持,这些似乎更容易理解原作者的意图。

Opened up Reflector. 打开Reflector。 HasValue is a lookup on a boolean flag which is set when the value is changed. HasValue是对布尔标志的查找,该标志在值更改时设置。 So in terms of cycles a lookup is going to be faster then compare. 因此,就周期而言,查找比比较更快。

public Nullable(T value)
{
    this.value = value;
    this.hasValue = true;
}

private bool hasValue;

internal T value;

public bool HasValue
{
    get
    {
        return this.hasValue;
    }
}

它们都是相同的,但我会在两者上使用前一个版本,因为它在语言中更常见:与null比较并转换为类型。

我通常倾向于倾向于两个场景中的第一个选项,因为它更倾向于面向对象的“原始”(这实际上就是我们想要的),但它真的无关紧要

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

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