GetValueOrDefault如何工作?
我负责一个LINQ提供程序,它对C#代码执行一些运行时评估。 举个例子:
int? thing = null; accessor.Product.Where(p => p.anInt == thing.GetValueOrDefault(-1))
目前上面的代码不能与我的LINQ提供程序一起使用,因为thing
为null。
虽然我已经使用C#很长时间了,但我不知道如何实现GetValueOrDefault,因此我应该如何解决这个问题。
所以我的问题是: GetValueOrDefault
如何在调用它的实例为空的情况下工作? 为什么不抛出NullReferenceException
?
接下来的问题:我应该如何使用reflection来复制对GetValueOrDefault
的调用,因为我需要处理空值。
thing
不是null
。 由于结构不能为null
,因此Nullable
不能为null
。
事情是……它只是编译魔术。 你认为它是null
。 实际上, HasValue
只是设置为false
。
如果你调用GetValueOrDefault
它会检查HasValue
是true
还是false
:
public T GetValueOrDefault(T defaultValue) { return HasValue ? value : defaultValue; }
不抛出NullReferenceException
,因为没有引用。 GetValueOrDefault
是Nullable
结构中的一个方法,因此您使用它的是值类型,而不是引用类型。
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; } } }
它产生输出:产品-1 – -1