GetValueOrDefault如何工作? [英] How does GetValueOrDefault work?

查看:59
本文介绍了GetValueOrDefault如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我负责LINQ提供程序,该提供程序对C#代码执行一些运行时评估.例如:

I'm responsible for a LINQ provider which performs some runtime evaluation of C# code. As an example:

int? thing = null;
accessor.Product.Where(p => p.anInt == thing.GetValueOrDefault(-1))

由于 thing 为空,当前以上代码不适用于我的LINQ提供程序.

Currently the above code doesn't work with my LINQ provider due to thing being null.

我使用C#已有很长时间了,但我不知道如何实现GetValueOrDefault,因此不知道该如何解决.

While I've been working with C# for a long time, I don't know how GetValueOrDefault is implemented and therefore how I should resolve this.

所以我的问题是: GetValueOrDefault 在调用它的实例为null的情况下如何工作?为什么不抛出 NullReferenceException ?

So my question is: how does GetValueOrDefault work in the case that the instance on which it is called is null? Why isn't a NullReferenceException thrown?

一个后续问题:鉴于我需要处理空值,我应该如何使用反射复制对 GetValueOrDefault 的调用.

A follow on question: how should I go about replicating a call to GetValueOrDefault using reflection, given that I need to handle null values.

推荐答案

事物不是 null .由于结构不能为 null ,因此 Nullable< int> 不能为 null .

thing isn't null. Since structs can't be null, so Nullable<int> can't be null.

问题是...这只是编译器的魔术.您认为 null .实际上, HasValue 只是设置为 false .

The thing is... it is just compiler magic. You think it is null. In fact, the HasValue is just set to false.

如果您致电 GetValueOrDefault 它会检查 HasValue true 还是 false :

public T GetValueOrDefault(T defaultValue)
{
    return HasValue ? value : defaultValue;
}

这篇关于GetValueOrDefault如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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