如果你愿意操作 IL 支持模块初始化器
If you are willing to manipulate IL supports Module Initializers
blogs.msdn/b/junfeng/archive/2005/11/19/494914.aspx
tech.einaregilsson/2009/12/16/module-initializers-in-csharp/
Silverlight 和 Windows Phone 7 是否支持模块初始值设定项?
Are Module initializers supported in Silverlight and Windows Phone 7?
推荐答案只有 C++/CLI 支持模块初始值设定项.这只是间接的,它使用它们来启动 CRT 并初始化非托管变量和对象.你必须写在IL.我试过了,它在 Silverlight 4 上工作得很好:
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 } }这是一个愚蠢的例子,模块初始值设定项设置了 Class1 的静态字段.然后,我在示例 Silverlight 应用程序中创建了 Class1 的实例,并使用调试器验证了该值.
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.
这个完全相同的代码在 Windows Phone 模拟器中不能工作.我应该修改了 TargetFrameworkAttribute,实际上并没有尝试这个.我怀疑这是问题的根源.
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.
更多推荐
Silverlight 和 Windows Phone 7 是否支持模块初始值设定项?
发布评论