简体   繁体   中英

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. But what type I have to use when the variable defines as class field?

Of course IEnumerable<Goods> doesn't go well. Tryed to use IEnumerable<object> but result is the same.

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

But it seems class Good (strange name) is a better option here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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