gpt4 book ai didi

c# - 是C# a=b=c;等于 b=c;一个= c;而 C++ 是 b=c;一=乙;?

转载 作者:行者123 更新时间:2023-11-30 13:10:02 26 4
gpt4 key购买 nike

换句话说,C# operator= 将返回正确的值,不是吗?但是 C++ 通常返回左值,对吗?

最佳答案

不是,赋值表达式的结果是赋值,不是右边的表达式。所以考虑一下:

    byte a;
int b;
byte c = 10;

a = b = c; // Fails to compile

编译失败是因为虽然 b = c 是有效的,但它是 int 类型的表达式,因此不能分配给 abyte 类型。

来自 C# 4 语言规范,第 7.17.1 节:

The result of a simple assignment expression is the value assigned to the left operand. The result has the same type as the left operand and is always classified as a value.

编辑:这里证明它是分配给使用的 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
}
}

a = b = c; 语句等同于:

BType tmp = c;
b = tmp;
a = tmp;

所以 b 的值之后不会读取(它不等同于 b = c; a = b;)- 所以如果 b 实际上是一个属性,那么除了副作用之外,该属性的行为将是无关紧要的。它是 在对 b 的赋值中使用的任何值,它也在对 a 的赋值中使用。

在这种情况下,对 b 的赋值需要从 ACTypeBType 的转换,从而创建一个 BType值=50。对 a 的赋值需要从 BTypeACType 的转换,这会创建一个值为 25 的 ACType

关于c# - 是C# a=b=c;等于 b=c;一个= c;而 C++ 是 b=c;一=乙;?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5590392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com