C# operator overloading does not work
These is my code:
public static Symbol operator + (Symbol op1, Symbol op2)
{
Symbol op3 = new Symbol() { op3.type = Type.Value };
object o1 = null;
object o2 = null;
object replacement;
try
{
o1 = op1.value.Value;
o2 = op2.value.Value;
if (o1 is string || o2 is string)
replacement = o1.ToString() + o2.ToString();
else if (o1 is double &&开发者_StackOverflow社区; o2 is double)
replacement = (double)o1 + (double)o2;
else
throw new Exception("only to be caught");
}
catch
{
op3.type = Type.Invalid;
op3.value = null;
replacement = op3;
}
Debug.WriteLine(String.Format("ExpressionEvaluator {0} + {1} = {2}", o1, o2, replacement));
op3.value = new Naked(replacement, typeof(bool));
return op3;
}
I gate the following error: One of the parameters of a binary operator must be the containing type
Any idea what is wrong?
Based on the error it sounds like you declared your operator+
inside a type other than Symbol
. C# requires that at least one of the types listed in the binary operator be the type in which the binary operator is defined
Update
As Eric pointed out, when the declaring type is a struct
(named say S) then one of the operands must be S
or S?
That means that the operator has to be declared in the Symbol
class.
精彩评论