使用Mono.Cecil检查属性类型是否重载==运算符

时间:2015-08-19 13:04:26

标签: c# code-injection cil mono.cecil

我使用Mono.Cecil编写一个程序,将一些IL代码注入属性设置器。问题是我需要在IL内使用属性上的相等运算符。例如:

public class SomeClass
{
    private int _property1;

    public int Property1 
    {
        get { return _property1; }
        set { _property1 = value; }
    }

    private string _property2;

    public string Property2
    {
        get { return _property2; }
        set { _property2 = value; }
    }
}

我需要的IL代码注入那些setter就像:

if (value != _property1)
{
   //DO SOME STUFF
}

同样适用于Property2。问题是Property2类型为string,它会重载==运算符,而IL代替ceq代码需要调用op_Equality。我的问题是:有没有办法检查使用==在属性类型上是否覆盖Mono.Cecil运算符?

1 个答案:

答案 0 :(得分:0)

嗯,实际上很容易。 我创建了一个类

 public class Foo
    {
        public static bool operator ==(Foo a, Foo b)
        {
            if (System.Object.ReferenceEquals(a, b))
            {
                return true;
            }
            if (((object)a == null) || ((object)b == null))
            {
                return false;
            }
            return a == b;
        }

        public static bool operator !=(Foo a, Foo b)
        {
            return !(a == b);
        }
    }

编译并在mono.cecil中查看它

 AssemblyDefinition assembly = AssemblyDefinition.ReadAssembly(path);
            foreach (var item in assembly.Modules)
            {
                foreach (var type in item.Types)
                {
                    foreach (var method in type.Methods)
                    {
                        if (method.IsStatic && method.IsSpecialName && method.IsPublic && method.Name.Contains("op_Equality"))
                        {
                            //that type overides == operator
                        }
                    }
                }
            }