换句话说,C#operator =会返回正确的值,不是吗?但是C++通常会返回左边的值,对吧?
Jon*_*eet 10
不,赋值表达式的结果是赋值,而不是右边的表达式.所以考虑一下:
byte a;
int b;
byte c = 10;
a = b = c; // Fails to compile
Run Code Online (Sandbox Code Playgroud)
这无法编译,因为虽然b = c它是有效的,但它是一个类型的表达式int,然后不能分配给a哪个类型byte.
从C#4语言规范,第7.17.1节:
简单赋值表达式的结果是赋给左操作数的值.结果与左操作数的类型相同,并且始终归类为值.
编辑:这里证明它b是使用的值,而不是值c:
using System;
class ACType
{
public int Value { get; set; }
public static implicit operator BType(ACType ac)
{
return new BType { Value = ac.Value / 2 };
}
}
class BType
{
public int Value { get; set; }
public static implicit operator ACType(BType b)
{
return new ACType { Value = b.Value / 2 };
}
}
class Test
{
static void Main()
{
ACType a, c;
BType b;
c = new ACType { Value = 100 };
a = b = c;
Console.WriteLine(a.Value); // Prints 25
}
}
Run Code Online (Sandbox Code Playgroud)
该a = b = c;声明相当于:
BType tmp = c;
b = tmp;
a = tmp;
Run Code Online (Sandbox Code Playgroud)
所以之后b不会读取它的值(它不等于b = c; a = b;) - 所以如果它b实际上是一个属性,那么除了副作用之外,属性的行为将是无关紧要的.它是分配中使用b的任何值,也用于赋值a.
在这种情况下,赋值b需要转换ACType为BType创建BType值为50的值.然后赋值到a需要转换BType为ACType,这将创建一个ACType值为= 25的值.