加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 19:59:39 所属栏目:百科 来源:网络整理
导读:我知道不允许将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.Produ
我知道不允许将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)

解决方法

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

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读