开发者

In C# how does one call a static method using emit

I am trying to using Emit to generate mapping code (mapping properties from one object to another). I have it working if the two types match (source and target), but I can't get it t开发者_C百科o work in an instance where the types don't match and I need to call a static method in the mapping. Below is code that I thought would work but I get a method does not exist error even though it does. I am guessing my emit call is incorrect. Any suggestions?

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);


You should be able to call it by using EmitCall with OpCodes.Call instead of CallVirt.


This is the line that's throwing the error?

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

Perhaps you could try

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

Perhaps parse takes an object as its parameter instead of a string?

What is the error message?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜