GetValueOrDefault如何工作?

时间:2015-04-14 11:38:23

标签: c# nullable

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

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

目前,由于thing为空,上述代码无法与我的LINQ提供程序一起使用。

虽然我长期以来一直在使用C#,但我不知道GetValueOrDefault是如何实现的,因此我应该如何解决这个问题。

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

接下来的问题:我应该如何使用反射来复制对GetValueOrDefault的调用,因为我需要处理空值。

4 个答案:

答案 0 :(得分:20)

thing不是null。由于结构不能null,因此Nullable<int>不能null

事情是......它只是编译魔术。您认为它是null。实际上,HasValue只是设置为false

如果您致电GetValueOrDefault,则会检查HasValuetrue还是false

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

答案 1 :(得分:1)

不会抛出NullReferenceException,因为没有引用。 GetValueOrDefaultNullable<T>结构中的方法,因此您使用它的是值类型,而不是引用类型。

GetValueOrDefault(T) method is simply implemented like this

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

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

答案 2 :(得分:0)

GetValueOrDefault ()可以防止由于null而发生的错误。如果传入数据为空,则返回0。

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

ageValue的值为零。

答案 3 :(得分:-1)

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

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; }
    }
}

它产生输出:产品-1 - -1