在C#中,如何使用调用一个静态方法发出

| 我正在尝试使用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);
    
已邀请:
您应该可以将
EmitCall
OpCodes.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将一个对象而不是字符串作为其参数? 错误消息是什么?     

要回复问题请先登录注册