简体   繁体   中英

How do I declare “Key” fields in C# anonymous types?

In VB.NET I'm used to doing things like this when creating anonymous types ( VB.NET anonymous types include the notion of Key Fields ):

Dim prod1 = New With {
    Key .Name = "paperclips",
    Key .Price = 1.29,
    .OnHand = 423
}

However, I haven't been able to find any way of doing this in C#, since it appears the Key keyword is not supported.

Is there any way to indicate in C# that I only want to compare some of the fields in anonymous type when looking for equality?

There is nothing like that in C#. In C#, all properties of anonymous types are read-only and participate in equality comparisons.

If you want to do something like this in C#, you will need to create your own (named) type.

c#中没有Key等价物。

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