匿名类的泛型列表列表

由网友(?莫默- Snow、默默?)分享简介:在C#3.0,你可以用下面的语法创建匿名类变种O =新{n = 1,名称=富};有没有办法将这些匿名类添加到泛型列表?例如:变种O =新{n = 1,名称=富};VAR 01 =新{n = 2,名称=酒吧};名单< VAR>名单=新的名单,其中,VAR>();list.Add(O);list.A...

在C#3.0,你可以用下面的语法创建匿名类

 变种O =新{n = 1,名称=富};
 

有没有办法将这些匿名类添加到泛型列表?

例如:

 变种O =新{n = 1,名称=富};
VAR 01 =新{n = 2,名称=酒吧};

名单< VAR>名单=新的名单,其中,VAR>();
list.Add(O);
list.Add(01);
 
Java 泛型

另外一个例子:

 名单,其中,VAR>名单=新的名单,其中,VAR>();

而 (....)
{
    ....
    list.Add(新{n = X,名称= Y});
    ....
}
 

解决方案

您可以这样做:

  VAR列表=新的[] {0,} O1 .ToList();
 

有很多剥皮这只猫的方式,但基本上他们将全部使用类型推断的地方 - 这意味着你必须要调用泛型方法(可能是作为一个扩展的方法)。另一个例子是:

 公共静态列表< T> CreateList< T>(PARAMS T []元)
{
     返回新的List< T>(元);
}

VAR列表= CreateList(O,01);
 

您明白了吧:)

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?

Example:

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);

Another Example:

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

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

解决方案

You could do:

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);

You get the idea :)

阅读全文

相关推荐

最新文章