gpt4 book ai didi

c# - C# 中的前缀和后缀运算符重载

转载 作者:行者123 更新时间:2023-11-30 20:19:09 25 4
gpt4 key购买 nike

以下代码存在运行时问题,通过分配后缀/前缀增量语句进行意外引用,如下面的代码所示。还有谁能建议我按照下面的建议在 C# 中将对象视为值类型的方法吗?

我相信代码有很好的文档记录,并附有说明每个重要状态的注释。请随时提出有关代码澄清或手头问题的任何问题。

提前致谢。

class Test {

public int x;

public Test(int x) { this.x=x; }
public Test() { x=0; }

static public Test operator++(Test obj) {
return new Test(obj.x+1);
}
}

// In implementing module
// Prefix/Postfix operator test for inbuilt (scalar) datatype 'int'
int x=2;
int y=++x; // 'y' and 'x' now both have value '3'
Console.WriteLine(x++); // Displays '3'
Console.WriteLine(++x); // Displays '5'
Console.WriteLine(ReferenceEquals(x,y)); // Displays 'False'


// Prefix/Postfix operator test of class type 'Test'
Test obj=new Test();
obj.x=1;
Console.WriteLine(obj++); // Must have displayed '1', displays the object type (Test.Test)
Console.WriteLine(++obj); // Must have displayed '3', again displays the object type (Test.Test)
Console.WriteLine(obj.x); // Displays '3' (as expected)

Test obj2=++obj; // Must have the value '4' and must NOT be the reference of obj
// Alternative solution to the above statement can be : 'Test obj2=new Test(++obj);' but isn't there a way to create a new value type in C# by the above statement ??!! (In C++, it can be acheived by overloading the '=' operator but C# doesn't allow it)
Console.WriteLine(obj2.x); // Displays '4' (as expected)
Console.WriteLine(ReferenceEquals(obj,obj2)); // Must display 'False' but displays 'True' showing that 'obj2' is the reference of 'obj'

最佳答案

基本上,您误解了这条线的工作原理:

Test obj2 = ++obj;

如果您考虑将运算符用作方法,那就像是在说:

obj = Test.operator++(obj);
obj2 = obj;

是的,您最终得到的是 objobj2 是同一个引用。 ++obj 的结果是 obj 的值 after 应用 ++ 运算符,但是那个 ++ 运算符也会影响 obj 的值。

如果你使用

Test obj2 = obj++;

那么这相当于:

Test tmp = obj;
obj = Test.operator++(obj);
obj2 = tmp;

此时,obj2的值将引用原始对象,而obj的值将引用具有更高的新创建的对象>x 值。

关于 Console.WriteLine 的结果的其余问题实际上是因为您没有覆盖 ToString()

关于c# - C# 中的前缀和后缀运算符重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39224491/

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