将匿名类型设置为null

Bug*_*tor 3 c# linq try-catch anonymous-types

我知道不允许将nonymous类型设置为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)
Run Code Online (Sandbox Code Playgroud)

Eri*_*ert 11

我同意其他答案,您应该考虑重构此代码或使用名义类型而不是匿名类型.

但是,有一种方法可以在匿名类型的变量中获取空引用.这很简单.

static List<T> GimmeANullListOf<T>(T t) { return (List<T>)null; }
...
var products = GimmeANullListOf(new { X = 1, Y = "hello" });
Run Code Online (Sandbox Code Playgroud)

这个技巧被称为"通过实例铸造",它很奇怪但合法.

  • @Jordão:我没跟着你.如何将编译器的内部知识考虑在内?这是合法的C#,任何符合要求的实现都需要具有此行为.为什么你认为这是实现定义的行为?什么"它会在组件中起作用吗?" 意思?我不明白你的问题中"工作"的含义. (3认同)

Who*_*hat 5

或者new Nullable<bool>()将很好地完成工作.