c# - 将匿名类型设置为 null

标签 c# linq try-catch anonymous-types

我知道不允许将匿名类型设置为 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/

相关文章:

c# - C# 泛型可以这么酷吗?

java - 捕获错误(而不是异常)有什么意义,因为程序不会由 JVM 启动

r - try catch for循环以进行回归

c++ - 我仍然可以从 catch block 中调用的函数中重新抛出异常吗?

c# - 从程序集 list 文件中读取程序集 GUID 的最快方法

c# - 映射 URL 或本地路径的数据结构

c# - 如何使用 Entity Framework/LINQ 从特定表中提取元组列表?

c# - 包含 namespace 的 XDocument

c# - 在 select new 中使用 List<> 加入 LINQ

c# - 将 XML 中的后代查询到 Linq