This afternoon, excitedly write a section of IL code, with reflector into C # code looked, no problem, then reference persisted to the hard disk dynamic assembly, want to try one of the methods, but run A system.accessviolationexception appears, prompting the message: "Try to read or write protected memory." This usually indicates that other memory is corrupted. ”。 Look at the error prompted a burst of head, the new computer memory damage is not likely, had to find the reason from their own programs.
After a burst of debugging, finally found the place to throw the exception, is in the constructor in the initialization of the random number of DateTime.Now.Millisecond error. Read for a long time, did not find why error, had to sacrifice a strong reflector, and then write the corresponding C # code:
Private Random rand = new Random (DateTime.Now.Millisecond);
Using reflector to view the system-generated IL code, the following statement is found:
. method public hidebysig specialname rtspecialname instance void
. ctor () cil managed
{
. maxstack 3
. Locals init (
[0] valuetype [mscorlib]system.datetime cs$0$0000)
l_0000:ldarg.0
l_0001:cal l valuetype [Mscorlib]system.datetime [mscorlib]
system.datetime::get_now ()
l_0006:stloc.0
l_0007:l DLOCA.S cs$0$0000
L_0009:call instance int32 [mscorlib]
system.datetime::get_millisecond () l_000e
: newobj instance void [Mscorlib]system.random::.ctor
(Int32)
l_0013:stfld class [Mscorlib]system.random
emitexamples.animal::rand
l_0018:ldarg.0
l_0019:call instance void [Mscorlib]system.object::.ctor ()
L_001e:nop
L_001f:ret
}
One of the differences between me and it is to add the two-il code in red. I've been doing this for almost a whole afternoon, but I'm pretty sure it's because of the difference between the value type and the reference type, and remember that when you load a reference type, you need to use the LDLOCA directive to write a few examples on your own, and there's nothing wrong with this method. But just know it but do not know why, in the garden for a long time, also did not find the relevant articles, had to give up, I hope to have the brothers know in the reply to point out, I will be extremely grateful!