GetValueOrDefault 如何工作?

问题描述 投票:0回答:5

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

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

目前,由于

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

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

所以我的问题是:在调用它的实例为空的情况下,

GetValueOrDefault
如何工作?为什么没有抛出
NullReferenceException

接下来的问题是:鉴于我需要处理空值,我应该如何使用反射复制对

GetValueOrDefault
的调用。

c# nullable
5个回答
56
投票

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

问题是……这只是编译器的魔法。你认为它是

null
。事实上,
HasValue
只是设置为
false

如果您调用

GetValueOrDefault
,它会检查
HasValue
是否为
true
false

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

12
投票

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

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

ageValue
的值将为零。


3
投票

A

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

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

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

因此,要复制该行为,您只需检查

HasValue
属性即可查看要使用的值。


0
投票

嗨,GetValueOrDefault() 已经在 C# 中出现了一段时间了。

Guid? nullableGuid = null;
Guid guid = nullableGuid.GetValueOrDefault()

-2
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.