Reputation:
I'm having troubles getting my MyClass
== operator
's method reference when specifying the comparison type while using Type.GetMethod()
, here is my code:
public class MyClass
{
public object Value { get; set; }
public MyClass(object inVal = null)
{
Value = inVal;
}
public static bool operator ==(MyClass a, string b)
{
// If one is null, but not both, return false.
if (((object)a == null) || ((object)b == null)) return false;
// Return true if the fields match:
return Convert.ToString(a.Value) == b;
}
public static bool operator !=(MyClass a, string b)
{
return !(a == b);
}
public static bool operator ==(MyClass a, bool b)
{
// If one is null, but not both, return false.
if ((object)a == null) return false;
// Return true if the fields match:
return Convert.ToBoolean(a.Value) == b;
}
public static bool operator !=(MyClass a, bool b)
{
return !(a == b);
}
}
A call to
var methodInfo = typeof(MyClass).GetMethod("op_Equality", new Type[] { typeof(bool) } )
or
var methodInfo = typeof(MyClass).GetMethod("op_Equality", new Type[] { typeof(string) } )
, returns NULL
, why is that? I expected a reference to the operator.
Upvotes: 0
Views: 483
Reputation: 216243
The equality/inequality operators works on two types,
(in your case the class type and the bool/string type),
you need to pass also the class type (in the correct order expected)
Type t1 = typeof(MyClass);
var methodInfo1 = t1.GetMethod("op_Equality",
new Type[] { t1, typeof(bool) } );
var methodInfo2 = t1.GetMethod("op_Equality",
new Type[] { t1, typeof(string) } );
Upvotes: 2
Reputation: 77285
The normal method expects a public instance method to look for. As yours are static methods, you should use an overload of GetType
that you can pass a BindingFlags
parameter of Static
.
Upvotes: 1