为什么我不能使用 C# 中的隐式类型来执行此操作?

发布于 2024-08-08 00:56:22 字数 149 浏览 2 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

剧终人散尽 2024-08-15 00:56:22

x.GetType() 是一个方法调用,在执行时评估。因此它不能用于像变量类型这样的编译时概念。我同意,偶尔能够执行类似的操作(将变量的编译时类型指定为其他地方的类型参数)会非常方便,但目前您不能。但我不能说我经常想念它。

但是,您可以这样做:

var x = new { a = "foobar", b = 42 };
var y = new[] { x };
var z = y.ToList();

您还可以编写一个简单的扩展方法来创建一个通用列表:(

public static List<T> InList<T>(this T item)
{
    return new List<T> { item };
}

如果需要,可以选择不同的名称:)

然后:

var x = new { a = "foobar", b = 42 };
var y = x.InList();

正如 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:

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.

抱猫软卧 2024-08-15 00:56:22

有多种方法可以使用通用方法来做到这一点:

public static List<T> CreateList<T>(T example) {
    return new List<T>();
}
...
var list = CreateList(x);

或者通过创建一个带有数据的列表,然后清空它......

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...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文