检查此指针是否在实例方法中被访问

Check if this pointer was accessed in an instance method

我正在尝试检测是否在点网实例方法中访问了 this 指针。可以是调用实例方法,访问成员变量等

目前正在研究反射:MethodBase.GetMethodBody 如果我能从 IL 中找出它。

使用Mono.Reflection

// using Mono.Reflection;
public static bool ContainsThis(MethodBase method)
{
    if (method.IsStatic)
    {
        return false;
    }

    IList<Instruction> instructions = method.GetInstructions();

    return instructions.Any(x => x.OpCode == OpCodes.Ldarg_0);
}

使用示例:

public class Foo
{
    private int bar;

    public int Bar
    {
        get { return bar; }
        set { }
    }

    public void CouldBeStatic()
    {
        Console.WriteLine("Hello world");
    }

    public void UsesThis(int p1, int p2, int p3, int p4, int p5)
    {
        Console.WriteLine(Bar);
        Console.WriteLine(p5);
    }
}

MethodBase m1 = typeof(Foo).GetMethod("CouldBeStatic");
MethodBase m2 = typeof(Foo).GetMethod("UsesThis");
MethodBase p1 = typeof(Foo).GetProperty("Bar").GetGetMethod();
MethodBase p2 = typeof(Foo).GetProperty("Bar").GetSetMethod();

bool r1 = ContainsThis(m1); // false
bool r2 = ContainsThis(m2); // true
bool r3 = ContainsThis(p1); // true
bool r4 = ContainsThis(p2); // false

记得 using Mono.Reflection.

啊...它是如何工作的... this 是一个 "hidden" 参数,第一个。要将 IL 代码中的参数加载到堆栈中,您可以使用 ldarg_#,其中 # 是参数编号。因此,在实例方法中,ldarg_0this 加载到堆栈中。