您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

C#中的重载赋值运算符

C#中的重载赋值运算符

听起来您应该使用 结构 而不是类…,然后创建隐式转换运算符,以及用于加法的各种运算符等。

这是一些示例代码

public struct VeLocity
{
    private readonly double value;

    public VeLocity(double value)
    {
        this.value = value;
    }

    public static implicit operator VeLocity(double value)
    {
        return new VeLocity(value);
    }

    public static VeLocity operator +(VeLocity first, VeLocity second)
    {
        return new VeLocity(first.value + second.value);
    }

    public static VeLocity operator -(VeLocity first, VeLocity second)
    {
        return new VeLocity(first.value - second.value);
    }

    // TODO: Overload == and !=, implement IEquatable<T>, override
    // Equals(object), GetHashCode and ToStrin
}

class Test
{
    static void Main()
    {
        VeLocity ms = 0;
        ms = 17.4;
        // The statement below will perform a conversion of 9.8 to VeLocity,
        // then call +(VeLocity, VeLocity)
        ms += 9.8;
    }
}

(作为一个旁注…我看不出它是如何真正代表速度的,因为肯定需要方向和幅度。)

c# 2022/1/1 18:21:34 有488人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶