Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 使用Mono.Cecil调用Convert.ToSingle(字符串参数)_.net_Mono.cecil_Valueconverter - Fatal编程技术网

.net 使用Mono.Cecil调用Convert.ToSingle(字符串参数)

.net 使用Mono.Cecil调用Convert.ToSingle(字符串参数),.net,mono.cecil,valueconverter,.net,Mono.cecil,Valueconverter,正如标题所说,我想用Mono.Cecil调用该方法,但我不知道如何做。如何用Mono.Cecil注入方法调用: 读取目标程序集 找到注入方法调用所需的点。要求的要点是 注入方法体的指令,其所有参数为 堆栈上的方法 找到一种注入方法 生成调用此方法的指令 在所需点后插入生成的指令(从索赔 2) 重写目标程序集 插入Convert.ToSingle(字符串)调用的代码示例: 目标方法 名称空间YourTargetNamespace { 公共类YourTargetClass { 公共单一YourTa

正如标题所说,我想用Mono.Cecil调用该方法,但我不知道如何做。

如何用
Mono.Cecil
注入方法调用:

  • 读取目标程序集
  • 找到注入方法调用所需的点。要求的要点是 注入方法体的指令,其所有参数为 堆栈上的方法
  • 找到一种注入方法
  • 生成调用此方法的指令
  • 在所需点后插入生成的指令(从索赔 2)
  • 重写目标程序集
  • 插入Convert.ToSingle(字符串)调用的代码示例:

    目标方法

    名称空间YourTargetNamespace
    {
    公共类YourTargetClass
    {
    公共单一YourTargetMethod()
    {
    var str=“1”;
    返回0;//Convert.ToSingle(str);
    }
    }
    }
    
    注入代码和测试在不同的程序集中进行

    [测试]
    public void InjectosingTest()
    {
    InjectConverToSingle();
    var engine=new YourTargetClass();
    Assert.That(engine.YourTargetMethod(),Is.EqualTo(1.0f));
    }
    public void invertosingle()
    {
    const string assemblyName=“YourTargetAssembly.dll”;
    var assembly=AssemblyDefinition.ReadAssembly(assemblyName);
    var type=assemble.MainModule.GetType(“YourTargetNamespace.YourTargetClass”);
    var method=type.Methods.First(m=>m.Name==“YourTargetMethod”);
    var il=method.Body.GetILProcessor();
    var requiredPoint=方法.Body.Instructions
    .First(指令=>instruction.OpCode.Code==Code.Ldstr&&
    (字符串)指令。操作数==“1”);
    var convertInstruction=CreateConvertInstruction(assembly.main模块);
    il.InsertAfter(要求的点,转换指令);
    InsertAfter(convertInstruction,Instruction.Create(OpCodes.Ret));
    编写(assemblyName);
    }
    公共指令CreateConvertInstruction(模块定义模块)
    {
    var typeConvert=module.Import(typeof(Convert));
    var methodToSingle=typeConvert.Resolve()
    .Methods.First(method=>method.Name==“ToSingle”&&
    method.Parameters.Count==1&&
    方法.Parameters[0]。ParameterType.FullName==module.TypeSystem.String.FullName);
    var importedMethodToSingle=module.Import(methodToSingle);
    返回指令.Create(opcode.Call,importedMethodToSingle);
    }