Program.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Reflection.Emit;
  6. namespace TestCases
  7. {
  8. struct MyStruct
  9. {
  10. public int x;
  11. public int y;
  12. }
  13. class Program
  14. {
  15. static void StructTest()
  16. {
  17. /*
  18. var inst = Activator.CreateInstance(typeof(MyStruct));
  19. var fi = typeof(MyStruct).GetField("x");
  20. fi.SetValue(inst, 23);
  21. var final = (MyStruct)inst;
  22. int x = 3;
  23. */
  24. var method = new DynamicMethod("set_struct_field", null, new Type[] { typeof(object) }, true);
  25. var il = method.GetILGenerator();
  26. il.Emit(OpCodes.Ldarg_0);
  27. il.Emit(OpCodes.Unbox, typeof(MyStruct));
  28. il.Emit(OpCodes.Ldc_I4, 23);
  29. il.Emit(OpCodes.Stfld, typeof(MyStruct).GetField("x"));
  30. il.Emit(OpCodes.Ret);
  31. var fn = (Action<object>)method.CreateDelegate(typeof(Action<object>));
  32. object inst = new MyStruct();
  33. fn(inst);
  34. int x = 3;
  35. }
  36. static void Main(string[] args)
  37. {
  38. StructTest();
  39. PetaJson.JsonEmit.Init();
  40. PetaTest.Runner.RunMain(args);
  41. }
  42. }
  43. }