.net - 是否有通用 CIL 代码将任何类型实例转换为字符串?

标签 .net cil il mono.cecil

是否可以编写将任何类型(值和引用)的实例转换为 System.String 的通用 CIL 指令?
特别是,我对将这些指令注入(inject)方法的 Mono.Cecil 代码感兴趣。

分析一个通用方法我想出了这些 Mono.Cecil 调用:
(它应该将第 i 个方法参数转换为字符串)

System.Reflection.MethodInfo to_string_method_info = typeof( System.Object ).GetMethod( "ToString" );
Mono.Cecil.MethodReference to_string_reference = injectible_assembly.MainModule.Import( to_string_method_info );

Mono.Cecil.TypeReference argument_type = method_definition.Parameters[ i ].ParameterType;
method_definition.Body.Instructions.Add( processor.Create( Mono.Cecil.Cil.OpCodes.Constrained, argument_type ) );
method_definition.Body.Instructions.Add( processor.Create( Mono.Cecil.Cil.OpCodes.Callvirt, to_string_reference ) );

但是,在调试时,我从“JIT 编译器遇到内部限制”的注入(inject)方法中得到一个异常。

最佳答案

编辑:

同样重要的是:注意我使用的是 typeof(object).GetMethod(...) ,而不是 typeof(T).GetMethod(...) - 你的电话argument_type.GetType().GetMethod( "ToString" );看起来很怀疑IMO。

我怀疑问题在于您正在加载本地/参数,而不是 地址 本地/参数的 - 在显示内容之前的行中。 Constrained需要这个才能正确执行静态调用实现;对于虚拟调用实现,它可以简单地取消引用 this 以获得实际引用。

除此之外:Constrained应该可以正常工作 - 见下文(特别注意 Ldarga_S )。当然,另一种选择是使用 Box ,但这将有更多的开销。 Constrained是调用ToString 的理想方式在任意类型上。

using System;
using System.Reflection.Emit;

public class RefTypeNoImpl { }
public class RefTypeImpl { public override string ToString() { return "foo"; } }
public struct ValTypeNoImpl { }
public struct ValTypeImpl { public override string ToString() { return "bar"; } }

static class Program
{
    static void Main()
    {
        Test<RefTypeNoImpl>();
        Test<RefTypeImpl>();
        Test<ValTypeNoImpl>();
        Test<ValTypeImpl>();
    }


    static void Test<T>() where T : new()
    {
        var dm = new DynamicMethod("foo", typeof(string), new[] { typeof(T) });
        var il = dm.GetILGenerator();
        il.Emit(OpCodes.Ldarga_S, 0);
        il.Emit(OpCodes.Constrained, typeof(T));
        il.Emit(OpCodes.Callvirt, typeof(object).GetMethod("ToString"));
        il.Emit(OpCodes.Ret);
        var method = (Func<T, string>)dm.CreateDelegate(typeof(Func<T, string>));
        Console.WriteLine(method(new T()));
    }
}

关于.net - 是否有通用 CIL 代码将任何类型实例转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18182756/

相关文章:

c# - 如何通过正则表达式检查允许 '[' 和 ']'

c# - 如何在DynamicMethod中调用DynamicMethod

c# - 在 C# 中拦截对属性 get 方法的调用

c# - 当我将一个类声明为内部类时,为什么 IL 将其显示为私有(private)类?

c# - CopyToNative 在哪里定义的?

c# - IL反汇编器能否显示嵌入式资源中的数据

c# - HttpClient - 检测内容类型

C# 正则表达式字符串解析

c# - 避免 PropertyGrid 的异常

c# - MSIL 问题(基本)