gpt4 book ai didi

c# - CIL 中的字符串生成器 (MSIL)

转载 作者:太空狗 更新时间:2023-10-29 23:19:26 26 4
gpt4 key购买 nike

我正在尝试生成采用 StringBuilder 的代码,并将类中所有属性的值写入字符串。我有以下内容,但我目前在以下代码中收到“无效方法标记”:

    public static DynamicAccessor<T> CreateWriter(T target) //Target class to *serialize*
{
DynamicAccessor<T> dynAccessor = new DynamicAccessor<T>();

MethodInfo AppendMethod = typeof(StringBuilder).GetMethod("Append", new[] { typeof(Object) }); //Append method of Stringbuilder

var method = new DynamicMethod("ClassWriter", typeof(StringBuilder), new[] { typeof(T) }, typeof(T), true);
var generator = method.GetILGenerator();
LocalBuilder sb = generator.DeclareLocal(typeof(StringBuilder)); //sb pointer


generator.Emit(OpCodes.Newobj, typeof(StringBuilder)); //make our string builder
generator.Emit(OpCodes.Stloc, sb); //make a pointer to our new sb


//iterate through all the instance of T's props and sb.Append their values.
PropertyInfo[] props = typeof(T).GetProperties();
foreach (var info in props)
{
generator.Emit(OpCodes.Callvirt, info.GetGetMethod()); //call the Getter
generator.Emit(OpCodes.Ldloc, sb); //load the sb pointer
generator.Emit(OpCodes.Callvirt, AppendMethod); //Call Append
}

generator.Emit(OpCodes.Ldloc, sb);
generator.Emit(OpCodes.Ret); //return pointer to sb

dynAccessor.WriteHandler = method.CreateDelegate(typeof(Write)) as Write;
return dynAccessor;
}

有什么想法吗?提前致谢:)

最佳答案

任何值类型的属性(int 等)都需要装箱;或者您将需要使用不同的 Append 重载。

还有:

  • 每次都需要加载对象(arg0)
  • StringBuilder.Append 是一个流畅的 API;您要么需要弹出该值,要么重新使用它:
  • 因此,您不需要该字段

(不过就我个人而言,我会返回一个 string,但是是“meh”)

像这样:

    DynamicAccessor<T> dynAccessor = new DynamicAccessor<T>();
MethodInfo AppendMethod = typeof(StringBuilder).GetMethod("Append", new[] { typeof(Object) }); //Append method of Stringbuilder

var method = new DynamicMethod("ClassWriter", typeof(StringBuilder), new[] { typeof(T) }, typeof(T), true);
var generator = method.GetILGenerator();
generator.Emit(OpCodes.Newobj, typeof(StringBuilder).GetConstructor(Type.EmptyTypes)); //make our string builder
//iterate through all the instance of T's props and sb.Append their values.
PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (var info in props)
{
generator.Emit(OpCodes.Ldarg_0);
generator.Emit(OpCodes.Callvirt, info.GetGetMethod()); //call the Getter
if (info.PropertyType.IsValueType)
{
generator.Emit(OpCodes.Box, info.PropertyType);
}
generator.Emit(OpCodes.Callvirt, AppendMethod); //Call Append
}
generator.Emit(OpCodes.Ret); //return pointer to sb

这生成等同于:

StringBuilder ClassWriter(T obj) {
return new StringBuilder.Append((object)obj.Foo).Append((object)obj.Bar)
.Append((object)obj.Blip).Append((object)obj.Blap);
}

关于c# - CIL 中的字符串生成器 (MSIL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1596989/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com