繁体   English   中英

为什么我不能在C#中创建一个匿名类型的列表<T>?

[英]why can't I create a list<T> of anonymous type in C#?

我是c#中anonymous types新手,我想创建一个包含3个变量的anonymous types liststring strint numDataTime time

但是,当我尝试使用这个问题的答案中的代码时: 匿名类的通用列表对我来说不起作用。

我使用了一个简单的Console application来执行此操作,我认为我收到了错误,因为我没有System.Core因为上述问题的评论中有人说:

(当然,您还需要对System.Core的引用。)

我不知道什么是System.Core ,如果我拥有它,那么它可能就是问题所在

我确实使用Systme.Linq

这是代码:

var list = new[] { str, num, time }.ToList();
list.add("hi", 5, DateTime.Now);

Console.WriteLine(list[0].num);

当我尝试指定variablestype (例如string str时,我也遇到了问题。

你缺少一些语法。 必须使用new{...}声明匿名类型。 必须在无法通过变量名称推断属性名称声明属性名称 (你也有一个错字Add ;它应该是大写)。

以下作品

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

工作 ,更清晰/更清洁:

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或遍历list / enumerable并打印默认的ToString ,这对你来说也没什么用。 这里没有通用约束来帮助。 此方法中的第三个语句将生成编译器错误

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会遇到同样的问题,我只是在澄清我的“无所事事”声明。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM