我想生成一個StringBuilder的代碼,並將一個類中的所有屬性的值寫入字符串。我有以下內容,但我目前在下面的代碼中收到「無效方法令牌」:在CIL(MSIL)中的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;
}
有沒有想法? 在此先感謝:)
(回答評論) – 2009-10-20 23:43:57