Original article: Dig a series of things that we don't commonly use in C # (4) -- gethashcode, expandoobject
In this article, we will continue to share the two interesting Methods: gethashcode and expandoobject.
1. gethashcode
It can be seen from msdn that it is used as a hash function of a specific type. That is to say, any object instance will have a hashcode of the int32 type and be stored in the FCL
In hashcollection, let's look at an example:
We can see that the hashcode of the two class instances is different, indicating that the two instances are not the same reference, and different hashcode is generated. Using this feature, do we have
Can we generate some random numbers?
1: generate with random in the for loop.
1 static void Main(string[] args) 2 { 3 var list = new List<int>(); 4 5 for (int i = 0; i < byte.MaxValue; i++) 6 { 7 list.Add(new Random().Next(0, byte.MaxValue)); 8 } 9 10 list.ForEach((i) =>11 {12 Console.WriteLine(i);13 });14 15 Console.Read();16 }
We know that random is pseudo-random, so a series of numbers are repeated. What should I do if I really want a random number? At this time, you can try hashcode.
2: hashcode in the For Loop
1 static void Main(string[] args) 2 { 3 var list = new List<int>(); 4 5 for (int i = 0; i < byte.MaxValue; i++) 6 { 7 list.Add(new Random().GetHashCode()); 8 } 9 10 list.ForEach((i) =>11 {12 Console.WriteLine(i);13 });14 15 Console.Read();16 }
However, we can see that we are constantly pushing to the managed service, so there is still a certain performance overhead for GC.
Ii. expandoobject
We know that PHP, ASP, and JS are both explanatory languages, saving compilation troubles. I used PHP for six months last year and then returned to C #, then it will be particularly uncomfortable with C # compilation.
Sometimes it takes more than 10 minutes to compile a solution of more than one hundred DLL files. The Weekly release date is released to the production environment through automated tools.
Environment, all need to be re-compiled, resulting in a lot of time spent on compilation, but after C #4.0, we use dynamic features, C # can also be written as Js.
For example, in the expandoobject class, we can dynamically append some attributes and methods to expandoobject through later binding, which is very interesting. However, note that
Once dynamic is enabled, the compiler does not recognize the code and waits for the JIT in the CLR to run it to achieve the compilation-free function.
1 static void Main(string[] args) 2 { 3 dynamic obj = new System.Dynamic.ExpandoObject(); 4 5 obj.Name = "hxc"; 6 7 obj.Age = 20; 8 9 obj.Call = new Action(() => { Console.WriteLine("call me!!!"); });10 11 obj.Call();12 13 Console.Read();14 }