匿名类型的目的是什么?目的、类型

2023-09-03 16:20:57 作者:宇宙限量版帅哥

什么是最好的用例匿名类型?

有似乎我,他们只在有限的范围内是有用的,例如一个类或一个功能。他们也很难被这种环境之外使用,因为没有思考,没有人会知道什么样的属性可在这些类型。

It would seem to me that they are only useful within a limited context, for example one class or one function. They can hardly be used outside of this context, because without reflection no one will know what properties are available on these types.

推荐答案

匿名类型的目的是在很窄的范围才能使用。那我已经为他们使用的大部分案件涉及的LINQ。

Anonymous types are intended to only be used in very narrow scopes. Most use cases that I've had for them involve Linq.

var result = from x in MyCollection
             select new 
             {
                 x.Prop1, 
                 x.Prop2
             };

另外,在LINQ的的情况下,到SQL - 使用匿名类型将通过只选择那些在匿名类型中使用的列生成不同的SQL。在上述情况下(如果它是一个LINQ to SQL的查询),它会产生类似从mytable的选择为prop1,prop2,而不是选择所有的字段。

Also, in the case of Linq to SQL - using anonymous types will generate different SQL by selecting only the columns that are used in the anonymous type. In the case above (if it were a Linq to SQL query), it would generate something like "select prop1, prop2 from mytable" instead of selecting all of the fields.

我从来没有在整个运行(还)的情况下,我想只需要声明一个新的匿名类型,我的code。我想,如果别的,也许这将是一个很好的利用了当地的常量?

I've never run across (yet) a situation where I wanted to just declare a new anonymous type in my code. I suppose if anything else, maybe it would be a good use for local constants?

var x = new
        {
            FirstName = "Scott",
            LastName = "Ivey"
        };