Are Module initializers supported in Silverlight and Windows Phone 7?
If you are willing to manipulate IL .net supports Module Initializers
http://blogs.msdn.com/b/junfeng/ar开发者_开发技巧chive/2005/11/19/494914.aspx
http://tech.einaregilsson.com/2009/12/16/module-initializers-in-csharp/
Are Module initializers supported in Silverlight and Windows Phone 7?
Only C++/CLI supports a module initializer. And that's only indirectly, it uses them to get the CRT started and to get unmanaged variables and objects initialized. You have to write on in IL. I tried, it worked just fine on Silverlight 4:
.assembly extern mscorlib
{
.publickeytoken = (7C EC 85 D7 BE A7 79 8E )
.ver 2:0:5:0
}
.assembly test
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78
63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 )
.custom instance void [mscorlib]System.Runtime.Versioning.TargetFrameworkAttribute::.ctor(string) = ( 01 00 18 53 69 6C 76 65 72 6C 69 67 68 74 2C 56
65 72 73 69 6F 6E 3D 76 34 2E 30 01 00 54 0E 14
46 72 61 6D 65 77 6F 72 6B 44 69 73 70 6C 61 79
4E 61 6D 65 0D 53 69 6C 76 65 72 6C 69 67 68 74
20 34 )
.hash algorithm 0x00008004
.ver 1:0:0:0
}
.method assembly specialname rtspecialname static void .cctor() cil managed
{
ldc.i4.s 42
stsfld int32 Example.Class1::test
ret
}
.class public auto ansi beforefieldinit Example.Class1
extends [mscorlib]System.Object
{
.field public static int32 test
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
.maxstack 8
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
}
}
Its a silly example, the module initializer sets a static field of Class1. I then created an instance of Class1 in a sample Silverlight app and verified the value with the debugger.
This exact same code did not work in the Windows Phone emulator. I should have modified the TargetFrameworkAttribute, did not actually try this. I doubt that it is the source of the problem.
精彩评论