C# 匿名类型列表的声明
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2327594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Declaration of Anonymous types List
提问by Krishna
Is there any way to declare a list object of anonymous type. I mean
有什么方法可以声明匿名类型的列表对象。我的意思是
List<var> someVariable = new List<var>();
someVariable.Add(
new{Name="Krishna",
Phones = new[] {"555-555-5555", "666-666-6666"}}
);
This is because I need to create a collection at runtime.
这是因为我需要在运行时创建一个集合。
采纳答案by JaredPar
It involves a bit of hackery but it can be done.
它涉及一些hackery,但可以做到。
static List<T> CreateListFromSingle<T>(T value) {
var list = new List<T>();
list.Add(value);
return list;
}
var list = CreateListFromSingle(
new{Name="Krishna",
Phones = new[] {"555-555-5555", "666-666-6666"}}
);
回答by Reed Copsey
You can't make a collection of an anonymous type like this.
您不能像这样制作匿名类型的集合。
If you need to do this, you'll need to either use List<object>
, or make a custom class or struct for your type.
如果您需要这样做,您需要使用List<object>
,或者为您的类型创建自定义类或结构。
Edit:
编辑:
I'll rephrase this:
我会改写这个:
Although, technically, it's possible to make a list of an anonymous type, I would strongly recommend never doing this. There is pretty much always a better approach, as doing this is just making code that is nearly unmaintainable. I highly recommend making a custom type to hold your values instead of using anonymous types.
尽管从技术上讲,可以制作匿名类型的列表,但我强烈建议永远不要这样做。几乎总是有更好的方法,因为这样做只会使代码几乎无法维护。我强烈建议使用自定义类型来保存您的值,而不是使用匿名类型。
A custom type will have all of the same capabilities (since anonymous types are defined, by the compiler, at compile time), but will be much more understandable by the developer who follows you...
自定义类型将具有所有相同的功能(因为匿名类型是由编译器在编译时定义的),但跟随您的开发人员将更容易理解......
And just to play, too, here's my entry for "code I'd never actually want to use in the real world":
只是为了玩,这里是我的条目“我永远不会真正想在现实世界中使用的代码”:
var customer = new { Name = "Krishna", Phones = new[] { "555-555-5555", "666-666-6666" } };
var someVariable = new[]{1}.Select(i => customer).ToList();
回答by Robert Massa
I don't think this is possible. Maybe in C# 4 using the dynamic keyword?
我不认为这是可能的。也许在 C# 4 中使用 dynamic 关键字?
回答by David Morton
You can make a list like this, but you'll again have to use some serious hackery, and you'll have to use some "type by example" situations. For example:
您可以像这样列出一个列表,但您将再次使用一些严肃的技巧,并且您将不得不使用一些“按示例类型”的情况。例如:
// create the first list by using a specific "template" type.
var list = new [] { new { Name="", Phones=new[] { "" } } }.ToList();
// clear the list. The first element was just an example.
list.Clear();
// start adding "actual" values.
list.Add(new { Name = "Krishna", Phones = new[] { "555-555-5555", "666-666-6666" } });
回答by Eric Lippert
In general you can use the (arguably bad-smelling) cast by example trick others have mentioned to create instances of any generic type parameterized with an anonymous type for the type argument. However, for List<T>
there is a slightly less gross way to do it:
通常,您可以使用其他人提到的示例技巧(可以说是不好的)来创建任何泛型类型的实例,这些泛型类型参数化为类型参数的匿名类型。但是,List<T>
有一种稍微不那么粗暴的方法来做到这一点:
var array = new[] {
new {
Name="Krishna",
Phones = new[] {"555-555-5555", "666-666-6666"}
}
};
var list = array.ToList();
Your sketch of a proposed syntax is similar to a feature we did not implement for C# 3 or 4, but we considered. We call the feature "mumble types", and it would go something like this:
您提出的语法草图类似于我们没有为 C# 3 或 4 实现的功能,但我们考虑过。我们称这个特性为“mumble 类型”,它会是这样的:
List<?> myList = new List<?>() {
new {
Name="Krishna",
Phones = new[] {"555-555-5555", "666-666-6666"}
}
};
We call it "mumble types" because of course you'd read it "myList is a new list of hrmmf". :-)
我们称它为“mumble 类型”,因为您当然会读到“myList 是一个新的 hrmmf 列表”。:-)
The idea is that the compiler would look at the initializers and do its best to figure out what the type could possibly be, just the same way as how "var" means "look at the initializer and figure out what the type of the variable is". Whether we'd use "var" as the "mumble" or "?" (which is similar to what Java does in a related feature), or something else is an open question.
这个想法是编译器会查看初始化程序并尽最大努力找出可能的类型,就像“var”的意思“查看初始化程序并找出变量的类型是什么”一样”。我们是否会使用“var”作为“mumble”或“?” (这类似于 Java 在相关特性中所做的),或者其他一些是一个悬而未决的问题。
In any event, I wouldn't hold my breath waiting for this feature if I were you. It hasn't made the cut for several language versions so far, but it will stay on the list of possibilities for a while longer I think. If, hypothetically speaking, we were to be designing future versions of the language. Which we might or might not be. Remember, Eric's musings about future versions of C# are for entertainment purposes only.
无论如何,如果我是你,我不会屏住呼吸等待这个功能。到目前为止,它还没有削减多种语言版本,但我认为它将在可能性列表中停留一段时间。假设,如果我们要设计该语言的未来版本。我们可能是也可能不是。请记住,Eric 对 C# 未来版本的思考仅用于娱乐目的。
回答by Jonathan
I spent quite a lot of time trying to find a way to save myself some time using a list of anonymous types, then realised it was probably quicker just to use a private class inside the current class...
我花了很多时间试图找到一种方法来使用匿名类型列表来节省一些时间,然后意识到在当前类中使用私有类可能会更快......
private class Lookup {
public int Index;
public string DocType;
public string Text;
}
private void MyMethod() {
List<Lookup> all_lookups = new List<Lookup> {
new Lookup() {Index=4, DocType="SuperView", Text="SuperView XML File"},
new Lookup() {Index=2, DocType="Word", Text="Microsoft Word Document"}
};
// Use my all_lookups variable here...
}
回答by Ian Mercer
Here's an approach that is somewhat cleaner than many of the other suggestions:
这是一种比许多其他建议更简洁的方法:
var list = Enumerable.Repeat(new { Name = "", Phones = new[] { "" } }, 0)
.ToList();
// ...
list.Add(new { Name = "Krishna",
Phones = new[] { "555-555-5555", "666-666-6666" } });
回答by Jai Kannah
How about dynamic?
动态呢?
List<dynamic> dynamicList = new List<dynamic>();
dynamicList.Add(new { Name = "Krishna", Phones = new[] { "555-555-5555", "666-666-6666" } });