为什么我不能使用 C# 中的隐式类型来执行此操作?
var x = new { a = "foobar", b = 42 };
List<x.GetType()> y;
有不同的方法来做我想做的事情吗?
如果没有,我真的看不到隐式类型的全部意义......
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
x.GetType()
是一个方法调用,在执行时评估。因此它不能用于像变量类型这样的编译时概念。我同意,偶尔能够执行类似的操作(将变量的编译时类型指定为其他地方的类型参数)会非常方便,但目前您不能。但我不能说我经常想念它。但是,您可以这样做:
您还可以编写一个简单的扩展方法来创建一个通用列表:(
如果需要,可以选择不同的名称:)
然后:
正如 Marc 所示,实际上不必这样做根本就是一种扩展方法。唯一重要的是编译器可以使用类型推断来计算方法的类型参数,这样您就不必尝试命名匿名类型。
隐式类型局部变量的用途有多种,但它们在 LINQ 中特别有用,因此您可以创建临时投影,而无需显式创建全新类型。
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:
You could also write a simple extension method to create a list generically:
(Pick a different name if you want :)
Then:
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:
or by creating a list with data and then emptying it...