GetValueOrDefault 是如何工作的?

How does GetValueOrDefault work?

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

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

目前,由于 thing 为空,上述代码不适用于我的 LINQ 提供程序。

虽然我已经使用 C# 很长时间了,但我不知道 GetValueOrDefault 是如何实现的,因此我应该如何解决这个问题。

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

后续问题:考虑到我需要处理空值,我应该如何使用反射复制对 GetValueOrDefault 的调用。

thing 不是 null。由于结构不能是 null,所以 Nullable<int> 不能是 null.

事情是......它只是编译器的魔法。你认为null。实际上, HasValue 只是设置为 false.

如果你调用 GetValueOrDefault 它会检查 HasValuetrue 还是 false:

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

A NullReferenceException 不会被抛出,因为没有引用。 GetValueOrDefaultNullable<T>结构中的一个方法,所以你用的是值类型,不是引用类型。

GetValueOrDefault(T)方法简单实现如下:

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

因此,要复制行为,您只需检查 HasValue 属性 以查看要使用的值。

我认为您的提供商工作不正常。我做了一个简单的测试,它工作正常。

using System;
using System.Linq;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            var products = new Product[] {
                new Product(){ Name = "Product 1", Quantity = 1 },
                new Product(){ Name = "Product 2", Quantity = 2 },
                new Product(){ Name = "Product -1", Quantity = -1 },
                new Product(){ Name = "Product 3", Quantity = 3 },
                new Product(){ Name = "Product 4", Quantity = 4 }
            };

            int? myInt = null;

            foreach (var prod in products.Where(p => p.Quantity == myInt.GetValueOrDefault(-1)))
            {
                Console.WriteLine($"{prod.Name} - {prod.Quantity}");
            }

            Console.ReadKey();
        }
    }

    public class Product
    {
        public string Name { get; set; }
        public int Quantity { get; set; }
    }
}

它作为输出产生:Product -1 - -1

GetValueOrDefault () 防止因为null 可能出现的错误。 Returns 如果传入数据为空,则为 0。

int ageValue = age.GetValueOrDefault(); // if age==null

ageValue 的值将为零。