当前位置:网站首页>LINQ Learning Series ----- 1.4 anonymous objects

LINQ Learning Series ----- 1.4 anonymous objects

2022-04-23 08:29:00 Wind god Shura envoy

This article continues from the previous one , This article briefly explains anonymous objects

One . Anonymous object Introduction

Code up :

var result=new {
    
             ID=1,
             Name=" Zhang San ",
             Age=23
           };

If you want to output the of this new object Age Content of property , It can make Console.WriteLine Drill down to the next level of the object ,Console.WriteLine(reuslt,1) that will do

Although anonymous objects have no object name , But it's still the type — The compiler will automatically generate a name for it . Code result Will point to an instance of the type automatically created above . This type has three properties :ID,Name,Age. These three properties are inferred from the declaration in the initializer .

Two . The consistency of anonymous object properties

var result1=new {
    ID=2,Name=" Li Si ",Age=33};
var result2=new {
    ID=3,Name=" Zhang San ",Age=11};
var result3=new {
    ID=3,Name=" Zhang San "};"

In the above code result1 and result2 Two different instances of the same type . however result3 and result1result2 It belongs to different types , Because the properties are inconsistent .

Be careful : If the order of attributes in the above code is inconsistent , Cause type It's also inconsistent .

3、 ... and . Restrictions on anonymous objects

  1. When using anonymous types , Leave the method that defines the type , We will no longer be able to strongly type instances of this anonymous type . To make this method , If we want to pass an instance of an anonymous type to a method , The type of this parameter of the passed method must be object.
  2. In addition to the methods that define anonymous types , We can only use reflection to further manipulate instances of this type .
  3. The return value type of the method defining the anonymous type must be object, Otherwise, anonymous types cannot be used as the return value of methods .
  4. Instances of anonymous types are immutable , Once an instance of an anonymous type is created , Then the attribute values of the instance will be determined forever , All attributes can only get, You can't set.

Four . The immutability of anonymous objects

Because anonymous types have immutable properties , So all its instances have stable hash values (hash code).

The immutable purpose of anonymous objects : Objects that will never change can greatly reduce the difficulty of concurrency control in program design . This is in the follow-up PLINQ Plays a key role in .( In the snapshot of an object at a certain time, there is no need to consider the possible inconsistent side effects ).

版权声明
本文为[Wind god Shura envoy]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230758281257.html