为什么我必须定义一个可交换操作符两次吗? [英] Why must I define a commutative operator twice?
问题描述
我不知道如果我必须定义一个可交换操作符(如 *
)的两倍!
I wonder if I must define a commutative operator (like *
) twice!
public static MyClass operator *(int i, MyClass m)
{
return new MyClass(i * m.Value);
}
public static MyClass operator *(MyClass m, int i)
{
return new MyClass(m.Value * i);
}
什么是这背后的逻辑是什么?
What's the logic behind this?
其他说明:亲爱的@马克的有关向量和矩阵乘法的回答是不错的的当且仅当我们假定操作类型不同!!!很明显,我们可以定义 *
运营商只有一次执行向量或矩阵乘法。的所以我觉得这是没有答案的。
Additional Descriptions: Dear @Marc's answer about Vector and Matrix multiplication was good if and only if we assume operand types are different !!! It's evident that we can define *
operator only once to perform Vector or Matrix multiplication. So I think this is not the answer.
@Marc:订单是运营商有时非常重要
@Marc: Order is sometimes important in operators.
是的,但这不等同与订单是在操作数有时非常重要!的上面这句话可以使用的情况下使用 +
运营商之前(或之后) *
运营商,这将导致不同的结果。例如:
Yes, but this is not equivalent with Order is sometimes important in operands! The above sentence may be used in case of using +
operator before (or after) *
operator that it will cause to different results. For example:
0 + 2 * 2 = 0 * 2 + 2
♦
假设我们定义 *
运营商为:
Assume that we've defined *
operator as:
public static MyClass operator *(MyClass m1, MyClass m2)
{
return new MyClass(m1.Value * m2.Value /* or some other kind of multiplication */);
}
我们的无法的重新定义它。
public static MyClass operator *(MyClass m2, MyClass m1) { ... }
如果这样,编译器会告诉我们,键入 MyClass的
已经定义了一个名为成员op_Multiply与。相同的参数类型
If so, compiler would tell us that type MyClass
already defines a member called 'op_Multiply' with the same parameter types.
现在,我们可以通过两种方式使用该操作符: M1 * M2
或 M2 * M1
,他们可能有依赖于乘法程序不同的结果。
Now, we can use this operator in two ways: m1 * m2
or m2 * m1
and they may have different results which depend on multiplication procedure.
推荐答案
订单是运营商有时重要的,经典的例子是subraction( -
)和除法( /
)。然而,它也可以应用到乘法:
Order is sometimes important in operators, the classic examples being subraction (-
) and division (/
). However, it can also apply to multiplication:
考虑,例如,他们的向量的 - X
是一个(2次; 1)载体,和是
是一个(1次; 2)载体。如果我们解读 *
矩阵乘法,那么 X * Y
是一个(2次; 2)载体,但 Y * X
是一个(1次; 1)载体
Consider, for example, that they are vectors - x
is a (2×1) vector, and y
is a (1×2) vector. If we interpret *
as matrix multiplication, then x * y
is a (2×2) vector, but y * x
is a (1×1) vector.
因此,C#编译器并不认为二元操作。是可交换的,即使它们的一般的有(除( +
),乘( *
),等等)。
As such, the C# compiler does not assume that binary operators are commutative, even if they commonly are (addition (+
), multiplication (*
), etc).
这篇关于为什么我必须定义一个可交换操作符两次吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!