在C#中动态替换(和备份)方法

时间:2017-06-16 16:34:31

标签: c# methods reflection replace

我需要动态更改特定属性并使用此snipplet:

var _oldMethod = typeof(TypeName).GetProperty("OldProperty", BindingFlags.Public | BindingFlags.Static).GetMethod;
var _newMethod = typeof(OwnTypeName).GetProperty("NewProperty", BindingFlags.Public | BindingFlags.Static).GetMethod;
ReplaceMethod(_oldMethod, _newMethod);

...

private static unsafe void ReplaceMethod(MethodInfo _oldMethod, MethodInfo _newMethod)
{
    var _oldMethodAddress = new IntPtr((int*)_oldMethod.MethodHandle.Value.ToPointer() + 2);
    var _destination = (uint*)_oldMethodAddress.ToPointer();
    *destination = (uint)_newMethod.MethodHandle.GetFunctionPointer().ToInt32();
}

不幸的是,这需要一些反编译来重新创建原始属性。我现在正在寻找的是复制和备份原始方法的可能性,并动态地用新方法替换旧方法或恢复原始方法。

有谁知道如何实现这个?

修改 我可能应该进一步澄清我的情况:

public static class ClassName
{
    public static bool Property
    {
      get
      {
        // Conditions
      }
    }
}

我无法访问ClassName,需要在特定情况下将Property强制为false,并且需要在其他情况下将其替换为原始返回值。我一直在使用上面提到的ReplaceMethod,但不想从头开始反编译和重建Property(而是原始属性的某种备份)

1 个答案:

答案 0 :(得分:0)

首先,您正在处理属性而不是方法。

执行此操作的一种简单方法是使用Func<>替换属性类型这将使你想要做的更容易。

private static void Main(string[] args)
{
    var a = new A();

    a.Property = Method1;
    Console.WriteLine(a.Property.Invoke());

    a.Property = Method2;
    Console.WriteLine(a.Property.Invoke());

    Func<string> oldMethod = a.Property;
    Console.WriteLine(oldMethod.Invoke());

    Console.ReadLine();
}

public class A
{
    public Func<string> Property { get; set; }
}

private static string Method1()
{
    return "Method1";
}

private static string Method2()
{
    return "Method2";
}

您可以根据需要多次更改方法,也可以将旧方法保存在一个变量中。