我是 c# 中匿名类型
的新手,我想创建一个包含 3 个变量的匿名类型
列表
:string str
, int num
, DataTime时间
.
然而,当我尝试使用这个问题的答案中的代码时:A generic list of anonymous class 它不会为我工作。
我使用了一个简单的 Console application
来完成它,我想我得到了错误
因为我没有 System.Core
因为上面问题的评论中有人说:
(You also need a reference to System.Core of course.)
我不知道什么是 System.Core
,如果我有它,那可能就是问题所在
我确实使用 Systme.Linq
。
代码如下:
var list = new[] { str, num, time }.ToList();
list.add("hi", 5, DateTime.Now);
Console.WriteLine(list[0].num);
当我尝试指定变量
的类型
时,我也遇到了问题
例如 string str
。
最佳答案
您缺少一些语法。必须使用 new{...}
声明匿名类型。当不能通过变量名推断出属性名时,必须声明属性名。(您在 Add
中也有拼写错误;它应该是大写的)。
下面works :
var str = "string";
var num = 5;
var time = DateTime.UtcNow;
// notice double "new"
// property names inferred to match variable names
var list = new[] { new { str, num, time } }.ToList();
// "new" again. Must specify property names since they cannot be inferred
list.Add(new { str = "hi", num = 5, time = DateTime.Now });
Console.WriteLine(list[0].num);
话虽如此,这还是很笨拙的。我建议编写一个具有所需属性的类,或使用 ValueTuple
。
这works并且更清晰/更干净:
var list = new List<(string str, int num, DateTime time)>();
// ValueTuple are declared in parens, method calls require parens as well
// so we end up with two sets of parens, both required
list.Add((str, num, time));
list.Add(("hi", 5, DateTime.Now));
Console.WriteLine(list[0].num);
另一个选择您自己的类或 ValueTuple
的原因是您不能将方法声明为接受匿名类型。换句话说,像这样的东西是无效的:
public void DoSomethingWithAnonTypeList(List<???> theList ) { ... }
没有什么*我可以用来替换 ???
因为匿名类型都是 internal
并且具有“无法说出的”名称。您将无法传递您的列表并用它做一些有意义的事情。那么有什么意义呢?
相反,我可以将方法声明为接受 ValueTuple
列表:
public void DoSomethingWithTupleList(List<(string, int, DateTime)> theList) {
Console.WriteLine(theList[0].Item1);
}
或使用命名元组:
public void DoSomethingWithTupleList(List<(string str, int num, DateTime time)> theList) {
Console.WriteLine(theList[0].time);
}
* 从技术上讲,您可以将匿名类型列表传递给通用方法。但是,您将无法访问各个属性。您能做的最好的事情是访问列表的 Count
或遍历列表/可枚举的,也许打印默认的 ToString
这也不会真正让您受益.这里没有通用约束可以提供帮助。此方法中的第三条语句将为 generate a compiler error :
public void DoSomethingGenerically<T>(List<T> theList) {
Console.WriteLine(theList.Count); // valid
Console.WriteLine(theList[0]); // valid, prints default ToString
Console.WriteLine(theList[0].num); // invalid! What's the point?
}
var list = new[] { new { str = "hi", num = 5, time = DateTime.Now } }.ToList();
// valid due to type inference, but see comments above
DoSomethingGenerically(list);
请注意,您在使用 ValueTuple
时也会遇到同样的问题,我只是在澄清我的“什么都不做”声明。
关于c# - 为什么我不能在 C# 中创建匿名类型的列表<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57131550/