简体   繁体   English

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

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

I am new to anonymous types in c#, and I want to create a list of anonymous types that contain 3 variables: string str , int num , DataTime time . 我是c#中anonymous types新手,我想创建一个包含3个变量的anonymous types liststring strint numDataTime time

however, when I try to use the code from this question`s answers: A generic list of anonymous class it won't work for me. 但是,当我尝试使用这个问题的答案中的代码时: 匿名类的通用列表对我来说不起作用。

I used a simple Console application to do it and I think I get the error because I don't have System.Core because someone in the comment of the question above said that: 我使用了一个简单的Console application来执行此操作,我认为我收到了错误,因为我没有System.Core因为上述问题的评论中有人说:

(You also need a reference to System.Core of course.) (当然,您还需要对System.Core的引用。)

and I don't know what is System.Core and if I have it so it might be the problem 我不知道什么是System.Core ,如果我拥有它,那么它可能就是问题所在

I do use Systme.Linq . 我确实使用Systme.Linq

here is the code: 这是代码:

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

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

I also face issues when I try to specify the type of the variables for example string str . 当我尝试指定variablestype (例如string str时,我也遇到了问题。

You are missing some syntax. 你缺少一些语法。 Anonymous types must be declared with new{...} . 必须使用new{...}声明匿名类型。 The property names must be declared when they cannot be inferred by a variable name. 必须在无法通过变量名称推断属性名称声明属性名称 (You also have a typo in Add ; it should be uppercase). (你也有一个错字Add ;它应该是大写)。

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

With that said, this is pretty clunky. 话虽如此,这非常笨重。 I'd suggest writing a class with the properties you want, or using ValueTuple . 我建议用你想要的属性编写一个类,或者使用ValueTuple

This works and is clearer/cleaner: 工作 ,更清晰/更清洁:

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

Another reason to prefer your own class or ValueTuple is that you cannot declare a method as accepting an anonymous type. 更喜欢自己的类或ValueTuple另一个原因是您不能将方法声明为接受匿名类型。 In otherwords, something like this is not valid: 。换句话说, 这样的事情是无效的:

public void DoSomethingWithAnonTypeList(List<???> theList ) { ... } 

There is nothing* I can put to replace the ??? 什么都没有*我可以用来取代??? as anonymous types are both internal and have "unspeakable" names. 因为匿名类型都是internal并且具有“难以言喻”的名称。 You wouldn't be able to pass your list around and do something meaningful with it. 您将无法通过列表并使用它执行有意义的操作 So what's the point? 那有什么意义呢?

Conversely, I can declare a method as accepting a list of ValueTuple s: 相反,我可以声明一个方法接受ValueTuple的列表:

public void DoSomethingWithTupleList(List<(string, int, DateTime)> theList) { 
     Console.WriteLine(theList[0].Item1);
} 

or using named tuples: 或使用命名元组:

public void DoSomethingWithTupleList(List<(string str, int num, DateTime time)> theList) { 
     Console.WriteLine(theList[0].time);
} 

* You can technically pass your list of anonymous types to a generic method. *您可以从技术上将匿名类型列表传递给通用方法。 However you won't be able to access the individual properties. 但是,您将无法访问各个属性。 The best you'd be able to do is access the list's Count or iterate over the list/enumerable and perhaps print the default ToString which doesn't really get you much either. 你能做的最好的事情就是访问列表的Count或遍历list / enumerable并打印默认的ToString ,这对你来说也没什么用。 There's not a generic constraint to help here. 这里没有通用约束来帮助。 The third statement in this method will 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); 

Do note that you'll have the same issue with ValueTuple , I'm just clarifying my "do nothing" statement. 请注意, ValueTuple会遇到同样的问题,我只是在澄清我的“无所事事”声明。

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

相关问题 建立清单 <T> T是在C#中使用LINQ的匿名类型 - Create a List<T> with T being an anonymous type using LINQ in C# 为什么我不能在 C# 中将匿名类型作为泛型返回,而我可以对方法参数执行相同的操作? - why I can't return anonymous type as generic in C#, while I can do the same for method parameters? 通过清单 <anonymous type> 到需要List的方法 <T> 在C#中 - Pass List<anonymous type> into method requiring List<T> in C# 将匿名类型转换为列表 <T> 在C#中使用Linq到SQL - Convert Anonymous Type to List <T> using Linq to SQL in C# 我们可以将匿名类型转换为列表吗 <T> 在C#中使用Linq实体? - Can we Convert Anonymous Type to List <T> using Linq to entity in C#? 为什么在声明常量时不能使用C#匿名类型? - Why C# anonymous type can't be used when declaring constants? 为什么在C#中我们不能将匿名对象包装在对象列表中? - Why in c# can't we wrap anonymous objects in list of objects? 为什么不能使用“类型”在C#中创建新变量? - Why can't I use a “Type” to create a new variable in C#? 在 C# 中,为什么匿名方法不能包含 yield 语句? - In C#, why can't an anonymous method contain a yield statement? 使用C#4.0中的匿名函数,为什么我无法定义内联委托 - With anonymous function in C# 4.0 why can't I define a delegate inline
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM