You need to enable JavaScript to run this app. 如何在C#中对this关键字使用自增(++)和自减(--)运算符
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中对this关键字使用自增(++)和自减(--)运算符

问题原因

++和--运算符要求操作数是可被赋值的变量、属性或索引器,而引用类型(class)的this关键字是只读的固定引用,不允许被重新赋值,所以直接写this++/this--会触发编译错误。

解决方案

如果你使用的是引用类型(class)

你自定义的自增/自减运算符本身会返回运算后的新实例,你只需要将新实例的成员同步到当前实例即可,示例代码如下:
假设你已经实现了自定义自增运算符:

public class MyClass
{
    public int Count { get; set; }
    
    // 自定义自增运算符
    public static MyClass operator ++(MyClass obj)
    {
        return new MyClass { Count = obj.Count + 1 };
    }
    
    public void SelfIncrease()
    {
        // 错误写法:this++;
        // 正确写法
        var newObj = this++;
        this.Count = newObj.Count;
        // 其他需要同步的属性/字段依次赋值即可
    }
}

注:引用类型的this不允许直接赋值,所以不能通过this = this++的写法直接替换当前实例

如果你使用的是值类型(struct)

值类型的this支持直接赋值,你可以直接用下面的写法实现需求:

public struct MyStruct
{
    public int Count { get; set; }
    
    public static MyStruct operator ++(MyStruct obj)
    {
        return new MyStruct { Count = obj.Count + 1 };
    }
    
    public void SelfIncrease()
    {
        // 该写法在struct中完全合法
        this = this++;
    }
}

内容的提问来源于stack exchange,提问作者Drifts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 23:24:02