我知道不允许将匿名类型设置为 null,但我该如何解决:
var products = null; //this cant be null, but somehow it must be declared in this outer scope, and not only inside the try-catch scope
try
{
products = (from p in repository.Products
select new { p.Product, p.ProductName }).ToList();
}
catch (Exception e)
{
return;
}
Console.WriteLine(products.FirstOrDefault().ProductName)
最佳答案
我同意其他答案,您应该考虑重构此代码或使用名义类型而不是匿名类型。
但是,有一种方法可以获得匿名类型变量中的空引用。这很容易。
static List<T> GimmeANullListOf<T>(T t) { return (List<T>)null; }
...
var products = GimmeANullListOf(new { X = 1, Y = "hello" });
这个技巧被称为“以身作则”,很奇怪但合法。
关于c# - 将匿名类型设置为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4774265/