简体   繁体   中英

How to define this 'var' type formally?

This code:

var items = query.ToList();

returns List<'a> where 'a is new { string a1, string a2 }

If I were to remove the var keyword, what would be a valid type definition to use here that keeps the names a1 and a2 ?

Nothing, because it's a list of an anonymous type. The very term "anonymous type" was chosen because the type doesn't have a name.

If you want to be able to use explicit typing, don't use an anonymous type. Either create your own type, or (in C# 7) use a C# tuple type. (The regular System.Tuple type wouldn't let you preserve the names you want.)

Your query is returning an anonymous type and therefore you do not know the type name at compilation time. If you want to remove the var project to a custom type instead of an anonymous type.

If you are in need to remove the var and know the type then do not use anonymous types. Have a look at: Why use anonymous types instead of creating a class


To use something along the lines of your comment: List< { string a1, string a2 } > look into Named Tuples in C# 7.0. You have have a look under C# 7.0 new features or Better naming in Tuple classes than "Item1", "Item2"

Something along the following:

List(string a1, string a2) result = (from item from collection
                                    select new (string a1, string a2) 
                                        { "firstString", "secondString" }).ToList();

The point about anonymous types is that they are not available at design time (when writing the code). They will be provided somewhere hidden by the compiler when the code is compiled. They have a name, and they are properly designed, but the types are inaccessible at design time by design.

That's why you are using var ; to let the compiler figure out what type this actually is, since the compiler is the only instance here that can tell you “where” the type is.

If you could replace the var by something real at design time, then you could also replace the new { … } by new Whatever { … } which would make this type no longer anonymous. – So if you want to use a type instead of var there, define an actual type yourself. Remember that doing that does not actually have a difference to what the compiler does for you anyway; it's just you now who is writing that class declaration.

唯一可行的方法是将结果向下转换为List<'a>类型的非匿名祖先IListIEnumerable

IList items = query.ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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