I have a generic method that calls operators by casting one of the operands to dynamic
.
There are two different calls:
//array is T[][]
//T is MyClass
array[row][column] != default(T) as dynamic
This works and calls static bool operator !=(MyClass a, MyClass b)
(even if both sides are null
).
What surprised me is the behaviour of the following line:
//array, a and b are T[][]
//T is MyClass
array[row][column] += a[line][i] * (b[i][column] as dynamic);
This calls
public static MyClass operator *(MyClass a, object b)
and
public static MyClass operator +(MyClass a, object b)
and not
public static MyClass operator *(MyClass a, MyClass b)
and
public static MyClass operator +(MyClass a, MyClass b)
.
Removing the (MyClass, object)
operators causes
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException wurde nicht behandelt.
HResult=-2146233088
Message=Der *-Operator kann nicht auf Operanden vom Typ "[...].MyClass" und "object" angewendet werden.
Source=Anonymously Hosted DynamicMethods Assembly
StackTrace:
bei CallSite.Target(Closure , CallSite , MyClass , Object )
bei System.Dynamic.UpdateDelegates.UpdateAndExecute2[T0,T1,TRet](CallSite site, T0 arg0, T1 arg1)
bei [...].MatrixMultiply[T](T[][] a, T[][] b) in
[...]
InnerException:
(ellipses mine).
Why?
Can I call the right operator without explicitly calling a T Operators.Add<T>(T a, T b)
method instead of the operator?
Update
public static T TestMethod<T>(this T a, T b)
{
return (T)(a * (b as dynamic));
}
This method in a separate assembly calls (or tries to call) operator *(T, object)
, if the same method is in the main assembly it correctly calls operator *(T, T)
.
The class I use as type parameter is internal
and the problem disappears when I change it to public
, so it seems to depend on the class' visibility towards the method.
operator *(T, object)
is called successfully even if the class isn't visible.