简体   繁体   English

是否应该为此匿名类型创建专用的类?

[英]Should I create a dedicated class for this anonymous type?

I have the following code in one of my functions 我的其中一项功能中包含以下代码

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

If it has been defined inside the method I would have used the var type. 如果它是在方法内部定义的,我将使用var类型。 But what type I have to use when the variable defines as class field? 但是,当变量定义为类字段时,我必须使用哪种类型?

Of course IEnumerable<Goods> doesn't go well. 当然, IEnumerable<Goods>并不顺利。 Tryed to use IEnumerable<object> but result is the same. 尝试使用IEnumerable<object>但结果相同。

Should I create a new class for this? 我应该为此创建一个新的类吗?

You are using an anonymous type . 您正在使用匿名类型 This can only exist within the scope of a function. 这只能存在于功能范围内。 If you want the results to be usable in a property, you'll need to create a real class for this. 如果希望结果在属性中可用,则需要为此创建一个真实的类。

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. 如果必须存储查询结果或将它们传递给方法边界之外,请考虑使用普通的命名结构或类而不是匿名类型。

if using C# 4 you can also use dynamic if creating a class isn't feasible... 如果使用C#4,则在创建类不可行的情况下也可以使用dynamic ...

But it seems class Good (strange name) is a better option here. 但是似乎在这里, Good (奇怪的名字)类是一个更好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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