反射发出以覆盖 C# 中的 ToString()

Reflection Emit to override ToString() in C#

有人可以帮我重写 ToString() 方法吗?

我要构建的C#代码如下:

  public override string ToString()
  {
        return $"{Id}, {Description}, {ParentId}";
  }

我发出的代码如下:

MethodBuilder toStringMethod = typebuilder.DefineMethod("ToString", 
MethodAttributes.Public | MethodAttributes.HideBySig | 
MethodAttributes.NewSlot | MethodAttributes.Virtual | 
MethodAttributes.Final,    CallingConventions.HasThis, typeof(string), 
Type.EmptyTypes);

ILGenerator il = toStringMethod.GetILGenerator();
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, "{0},{1},{2}");
il.Emit(OpCodes.Ldc_I4_4);
il.Emit(OpCodes.Call, getIdMethodeBuilder);
il.Emit(OpCodes.Call, getDescriptionMethodeBuilder);
il.Emit(OpCodes.Call, getParentIdMethodeBuilder);

il.Emit(OpCodes.Ret);
typebuilder.DefineMethodOverride(toStringMethod, typeof(object).GetMethod("ToString"));

提前致谢。

感谢@lasse。 我的代码更正如下:

  Type[] formatStringArgs = { typeof(string), typeof(int), typeof(string), typeof(int) };
   MethodInfo formatString = typeof(String).GetMethod("Format", formatStringArgs);

   il = toStringMethod.GetILGenerator();
   il.Emit(OpCodes.Nop);
   il.Emit(OpCodes.Ldstr, "{0},{1},{2}");

   il.Emit(OpCodes.Ldarg_0);
   il.Emit(OpCodes.Call, getIdMethodeBuilder);
   il.Emit(OpCodes.Box, typeof(Int32));

   il.Emit(OpCodes.Ldarg_0);                   
   il.Emit(OpCodes.Call, getDescriptionMethodeBuilder);

   il.Emit(OpCodes.Ldarg_0);
   il.Emit(OpCodes.Call, getParentIdMethodeBuilder);
   il.Emit(OpCodes.Box, typeof(Int32));

   il.Emit(OpCodes.Call, formatString);
   il.Emit(OpCodes.Ret);
   typebuilder.DefineMethodOverride(toStringMethod, 
   typeof(object).GetMethod("ToString"));

谢谢大家