我使用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
运算符?
答案 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
}
}
}
}