I'm just interested in people's opinions. When using nullable types in C# what is the best practice way to test for null:
bool isNull = (i == null);
or
bool isNull = !i.HasValue;
Also when assigning to a non-null type is this:
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.
Use the forms that were specially implemented for you by the C# team. 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.
Note that in terms of performance, both forms compile down to the same IL, ie:
int? i = 1;
bool isINull = i == null;
int j = (int)i;
Ends up like this after the C# compiler has got to it:
int? i = 1;
bool isINull = !i.HasValue;
int j = i.Value;
I would always use the (i==null) form. It expresses what you are doing.
WRT the second question, I think either form is fine. 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).
I haven't used Nullable Types in practice, but for the second, I'd actually suggest using j.GetValueOrDefault(). The documentation suggests that the latter would actually throw an InvalidOperationException in the event of a null value. Depending on the internal implementation of the explict cast operator for long?, the former might, too. I'd stick with GetValueOrDefault and treat the null/default case appropriately.
我倾向于使用第一个,因为它需要在其生命周期的后期得到支持,这些似乎更容易理解原作者的意图。
Opened up Reflector. HasValue is a lookup on a boolean flag which is set when the value is changed. 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比较并转换为类型。
我通常倾向于倾向于两个场景中的第一个选项,因为它更倾向于面向对象的“原始”(这实际上就是我们想要的),但它真的无关紧要
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.