gpt4 book ai didi

c# - 我应该为这个匿名类型创建一个专用类吗?

转载 作者:太空宇宙 更新时间:2023-11-03 20:20:01 25 4
gpt4 key购买 nike

我的一个函数中有以下代码

goodsQuery = db.Goods.Select(g => new { g.name, g.description, g.image, g.price });

如果它已在方法中定义,我会使用 var 类型。但是当变量定义为类字段时我必须使用什么类型?

当然IEnumerable<Goods>不顺利。尝试使用 IEnumerable<object>但结果是一样的。

我应该为此创建一个新类吗?

最佳答案

您正在使用 anonymous type .这只能存在于函数范围内。如果您希望结果在属性中可用,您需要为此创建一个真实的类。

You cannot declare a field, a property, an event, or the return type of a method as having an anonymous type. Similarly, you cannot declare a formal parameter of a method, property, constructor, or indexer as having an anonymous type. To pass an anonymous type, or a collection that contains anonymous types, as an argument to a method, you can declare the parameter as type object. However, doing this defeats the purpose of strong typing. If you must store query results or pass them outside the method boundary, consider using an ordinary named struct or class instead of an anonymous type.

关于c# - 我应该为这个匿名类型创建一个专用类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14216511/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com