gpt4 book ai didi

c# - 如何在我的类(class)中实现前置和后置自增/自减运算符?

转载 作者:行者123 更新时间:2023-12-02 11:17:17 25 4
gpt4 key购买 nike

我想重载 ++ 运算符,以在我的 C# 类中使用运算符重载来使用前增量和后增量。但只有后增量才有效。如何使这两个功能在我的类(class)中起作用?假设我做了一个 ABC 类 -

using System;
using System.Collections.Generic;
using System.Text;

namespace Test
{
class ABC
{
public int a,b;
public ABC(int x, int y)
{
a = x;
b = y;
}
public static ABC operator ++(ABC x)
{
x.a++;
x.b++;
return x;
}
}

class Program
{
static void Main(string[] args)
{
ABC a = new ABC(5, 6);
ABC b, c;
b = a++;
Console.WriteLine("After post increment values are {0} and {1} and values of b are {2} and {3}", a.a, a.b, b.a, b.b);// expected output a.a = 6, a.b = 7, b.a = 5, b.b = 6 but not get that
c = ++a;
Console.WriteLine("After pre increment values are {0} and {1} and values of c are {2} and {3}", a.a, a.b, c.a, c.b); // expected output a.a = 7, a.b = 7, c.a = 7, c.b = 8 works fine
Console.Read();
}
}
}

最佳答案

您的示例无法正确实现此一元运算符,如 17.9.1 一元运算符 中的 C# 规范中所指定:

Unlike in C++, this method need not, and, in fact, should not, modify the value of its operand directly.

这是您的示例,其中包含一些微单元测试:

using System;

class ABC
{
public int a,b;
public ABC(int x, int y)
{
a = x;
b = y;
}

public static ABC operator ++(ABC x)
{
x.a++;
x.b++;
return x;
}
}

class Program
{
static void Main()
{
var a = new ABC(5, 6);
if ((a.a != 5) || (a.b != 6)) Console.WriteLine(".ctor failed");

var post = a++;
if ((a.a != 6) || (a.b != 7)) Console.WriteLine("post incrementation failed");
if ((post.a != 5) || (post.b != 6)) Console.WriteLine("post incrementation result failed");

var pre = ++a;
if ((a.a != 7) || (a.b != 8)) Console.WriteLine("pre incrementation failed");
if ((pre.a != 7) || (pre.b != 8)) Console.WriteLine("pre incrementation result failed");

Console.Read();
}
}

您的代码失败是增量后的结果,这是由于您更改了作为参数传递的 ABC 实例而不是返回新实例。更正后的代码:

class ABC
{
public int a,b;
public ABC(int x, int y)
{
a = x;
b = y;
}

public static ABC operator ++(ABC x)
{
return new ABC(x.a + 1, x.b + 1);
}
}

关于c# - 如何在我的类(class)中实现前置和后置自增/自减运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3282619/

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