是否有创建匿名类型的泛型列表的把戏? [英] Is there a trick in creating a generic list of anonymous type?
问题描述
有时我需要使用一个元组,例如我有坦克和他们的目标坦克列表(他们在他们以后或者类似的东西追逐) > 列表与LT元组LT;罐,箱>> MYLIST =新的List<元组LT;罐,箱>>();
,然后当我遍历列表我通过
$访问它们b $ b
MYLIST [I] ... .item1
MYLIST [I] ... .item2
这是非常混乱,我总是忘了是什么ITEM1,什么是项目2,如果我可以通过访问它们:
MYLIST [I] ... .AttackingTank
MYLIST [I] ... .TargetTank
这将是更加清晰,有没有办法做到这一点没有定义一个类:
MyTuple
{
公共坦克AttackingTank;
公共坦克TargetTank;
}
我想避免定义这个类,因为那时我将不得不定义许多不同。在不同的场景类的,我可以做一些绝招,使这个匿名
是这样的:
VAR K =新的{名称=我,电话= 123};
mylist.Add(K);
这是我没有一个类型传递给列表时,我把它定义课程的问题
您可以创建一个匿名类型列表为空,然后使用它,享受充满intelisence和编译时检查:
VAR列表= Enumerable.Empty<对象>()
。选择(R =>新建{A = 0, b = 0})//匿名类型
.ToList的原型();
list.Add(新{A = 4,B = 5}); //将实际值
Console.Write(名单[0] .A);
Sometimes i need to use a Tuple, for example i have list of tanks and their target tanks (they chase after them or something like that ) :
List<Tuple<Tank,Tank>> mylist = new List<Tuple<Tank,Tank>>();
and then when i iterate over the list i access them by
mylist[i].item1 ...
mylist[i].item2 ...
It's very confusing and i always forget what is item1 and what is item2, if i could access them by :
mylist[i].AttackingTank...
mylist[i].TargetTank...
It would be much clearer, is there a way to do it without defining a class:
MyTuple
{
public Tank AttackingTank;
public Tank TargetTank;
}
I want to avoid defining this class because then i would have to define many different classes in different scenarios, can i do some "trick" and make this anonymous.
Something like :
var k = new {Name = "me", phone = 123};
mylist.Add(k);
The problem of course that i don't have a type to pass to the List when i define it
You can create an empty list for anonymous types and then use it, enjoying full intelisence and compile-time checks:
var list = Enumerable.Empty<object>()
.Select(r => new {A = 0, B = 0}) // prototype of anonymous type
.ToList();
list.Add(new { A = 4, B = 5 }); // adding actual values
Console.Write(list[0].A);
这篇关于是否有创建匿名类型的泛型列表的把戏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!