Anonymous Types in C#

折月煮酒 提交于 2020-01-11 00:42:08

问题


// x is compiled as an int 
var x = 10;

// y is compiled as a string 
var y = "Hello";

// z is compiled as int[] 
var z = new[] { 0, 1, 2 };

but

// ano is compiled as an anonymous type 
var ano = new { x1 = 10, y1 = "Hello" };

ano object's properties created are read-only . I want to figure it out why those properties are read only. suggestions are appreciated ?

EDIT:

var ano1 = new { x1 = 10, y1 = "Hello" };

var ano2 = new { x1 = 10, y1 = "Hello" };

Is that if the new anonymous type has the same number and type of properties in the same order will it be of the same internal type as the first ?


回答1:


var does not mean "use an anonymous type", it means "Compiler, go figure out the type for me!". In the first three cases, the type is actually a "named" type - System.Int32, System.String, and System.Int32[] (in the last case the type of array's elements is also deduced by the compiler from the type of array elements that you put in the initializer).

The last case is the only one where an anonymous type is used. It is by design that C#'s anonymous types are immutable. The primary case for adding them in the language in the first place has been introduction of LINQ, which does not need mutability in cases when anonymous types are produced. In general, immutable classes tend to give designers less problems, especially when concurrency is involved, so designers of the language decided to go with immutable anonymous types.




回答2:


Anonymous types are immutable, i.e Can't change.

What is an immutable type?

Eric Lippert's Blog




回答3:


Interesting statement from here. And an alternative is found here.

... [B]y ensuring that the members do not change, we ensure that the hash is constant for the lifetime of the object.This allows anonymous types to be used with collections like hashtables, without actually losing them when the members are modified. There are a lot of benefits of immutabilty in that, it drastically simplifies the code that uses the object since they can only be assigned values when created and then just used (think threading)



来源:https://stackoverflow.com/questions/18816218/anonymous-types-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!