在c#中,如何使用emit调用静态方法?

本文关键字:emit 调用 静态方法 何使用 | 更新日期: 2023-09-27 17:50:32

我试图使用Emit生成映射代码(从一个对象映射属性到另一个对象)。如果两种类型匹配(源和目标),我让它工作,但是我不能让它在类型不匹配的实例中工作,我需要在映射中调用静态方法。下面是代码,我认为会工作,但我得到一个方法不存在错误,即使它确实存在。我猜我的emit调用是错误的。有什么建议吗?

foreach (var map in maps)
{
  il.Emit(OpCodes.Ldarg_1);
  il.Emit(OpCodes.Ldarg_0);
  il.EmitCall(OpCodes.Callvirt, map.SourceProperty.GetGetMethod(), null);
  if (map.SourceProperty.PropertyType == map.TargetProperty.PropertyType)
    il.EmitCall(OpCodes.Callvirt, map.TargetProperty.GetSetMethod(), null);
  else if (map.TargetProperty.PropertyType.Name == "ObjectId" && map.SourceProperty.PropertyType.Name.ToLower() == "string") {
    var method = typeof(ObjectId).GetMethod("Parse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder,  new Type[] { typeof(string) }, null);
    il.EmitCall(OpCodes.Callvirt, method , null);
  }
}
il.Emit(OpCodes.Ret);

在c#中,如何使用emit调用静态方法?

您应该能够通过使用EmitCallOpCodes.Call而不是CallVirt来调用它。

这是抛出错误的行吗?

var method = typeof(ObjectId).GetMethod("Parse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder,  new Type[] { typeof(string) }, null);

也许你可以试试

Type ObjectIDType = typeof(ObjectId);
MethodInfo method = ObjectIDType.GetMethod("Parse", new Type[] { typeof(string) });

也许parse接受一个对象作为它的参数而不是字符串?

错误信息是什么?