匿名类的通用列表 [英] A generic list of anonymous class

查看:21
本文介绍了匿名类的通用列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C# 3.0 中,您可以使用以下语法创建匿名类

In C# 3.0 you can create anonymous class with the following syntax

var o = new { Id = 1, Name = "Foo" };

有没有办法将这些匿名类添加到通用列表中?

Is there a way to add these anonymous class to a generic list?

示例:

var o = new { Id = 1, Name = "Foo" };
var o1 = new { Id = 2, Name = "Bar" };

List<var> list = new List<var>();
list.Add(o);
list.Add(o1);

另一个例子:

List<var> list = new List<var>();

while (....)
{
    ....
    list.Add(new {Id = x, Name = y});
    ....
}

推荐答案

你可以这样做:

var list = new[] { o, o1 }.ToList();

有很多方法可以给这只猫剥皮,但基本上它们都会在某处使用类型推断 - 这意味着您必须调用通用方法(可能作为扩展方法).另一个例子可能是:

There are lots of ways of skinning this cat, but basically they'll all use type inference somewhere - which means you've got to be calling a generic method (possibly as an extension method). Another example might be:

public static List<T> CreateList<T>(params T[] elements)
{
     return new List<T>(elements);
}

var list = CreateList(o, o1);

你明白了:)

这篇关于匿名类的通用列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆