Why can't I do this with implicit types in C#?
var x = new { a = "foobar", b = 42 };
List<x.GetType()> y;
Is there a 开发者_运维知识库different way to do what I want to do here?
If there's not, I don't really see all that much point in implicit types...
x.GetType()
is a method call, evaluated at execution time. It therefore can't be used for a compile-time concept like the type of a variable. I agree that occasionally it would be quite handy to be able to do something similar (specifying the compile-time type of a variable as a type argument elsewhere), but currently you can't. I can't say I regularly miss it though.
However, you can do:
var x = new { a = "foobar", b = 42 };
var y = new[] { x };
var z = y.ToList();
You could also write a simple extension method to create a list generically:
public static List<T> InList<T>(this T item)
{
return new List<T> { item };
}
(Pick a different name if you want :)
Then:
var x = new { a = "foobar", b = 42 };
var y = x.InList();
As Marc shows, it doesn't actually have to be an extension method at all. The only important thing is that the compiler can use type inference to work out the type parameter for the method so that you don't have to try to name the anonymous type.
Implicitly typed local variables are useful for a variety of reasons, but they're particularly useful in LINQ so that you can create an ad-hoc projection without creating a whole new type explicitly.
There are ways of doing this with a generic method:
public static List<T> CreateList<T>(T example) {
return new List<T>();
}
...
var list = CreateList(x);
or by creating a list with data and then emptying it...
精彩评论