C#中的重载赋值运算符 [英] Overloading assignment operator in C#

查看:308
本文介绍了C#中的重载赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道=运算符不能重载,但是必须有一种方法可以在这里执行我想要的操作:

I know the = operator can't be overloaded, but there must be a way to do what I want here:

我正在创建代表定量单位的类,因为我正在做一些物理工作.显然,我不能只是从基元继承而已,但我希望我的类的行为完全像基元一样-我只是希望它们的键入方式不同.

I'm just creating classes to represent quantitative units, since I'm doing a bit of physics. Apparently I can't just inherit from a primitive, but I want my classes to behave exactly like primitives -- I just want them typed differently.

所以我可以去

Velocity ms = 0;
ms = 17.4;
ms += 9.8;

我不确定该怎么做.我以为我会写一些像这样的类:

I'm not sure how to do this. I figured I'd just write some classes like so:

class Power
{
    private Double Value { get; set; }

    //operator overloads for +, -, /, *, =, etc
}

但是显然我不能重载赋值运算符.有什么办法可以使我获得这种行为?

But apparently I can't overload the assignment operator. Is there any way I can get this behavior?

推荐答案

听起来您应该使用 struct 而不是类...,然后还要创建一个隐式转换运算符作为各种加法运算符等.

It sounds like you should be using a struct rather than a class... and then creating an implicit conversion operator, as well as various operators for addition etc.

下面是一些示例代码:

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;
    }
}

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

(As a side-note... I don't see how this really represents a velocity, as surely that needs a direction as well as a magnitude.)

这篇关于C#中的重载赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆