C#中的重载赋值运算符

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


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


这样我就可以走了


Velocity ms = 0;

ms = 17.4;

ms += 9.8;

等等


我不确定该怎么做。我想我只是写一些像这样的类:


class Power

{

    private Double Value { get; set; }


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

}

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


慕的地8271018
浏览 836回答 3
3回答

慕码人8056858

听起来您应该使用结构而不是类...,然后创建隐式转换运算符,以及用于加法的各种运算符等。这是一些示例代码:public struct Velocity{&nbsp; &nbsp; private readonly double value;&nbsp; &nbsp; public Velocity(double value)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; this.value = value;&nbsp; &nbsp; }&nbsp; &nbsp; public static implicit operator Velocity(double value)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return new Velocity(value);&nbsp; &nbsp; }&nbsp; &nbsp; public static Velocity operator +(Velocity first, Velocity second)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return new Velocity(first.value + second.value);&nbsp; &nbsp; }&nbsp; &nbsp; public static Velocity operator -(Velocity first, Velocity second)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return new Velocity(first.value - second.value);&nbsp; &nbsp; }&nbsp; &nbsp; // TODO: Overload == and !=, implement IEquatable<T>, override&nbsp; &nbsp; // Equals(object), GetHashCode and ToStrin}class Test{&nbsp; &nbsp; static void Main()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Velocity ms = 0;&nbsp; &nbsp; &nbsp; &nbsp; ms = 17.4;&nbsp; &nbsp; &nbsp; &nbsp; // The statement below will perform a conversion of 9.8 to Velocity,&nbsp; &nbsp; &nbsp; &nbsp; // then call +(Velocity, Velocity)&nbsp; &nbsp; &nbsp; &nbsp; ms += 9.8;&nbsp; &nbsp; }}(作为一个旁注...我看不出它是如何真正代表速度的,因为肯定需要方向和幅度。)

繁星coding

您可以创建隐式转换运算符。在MSDN上有一个页面,有一个很好的例子。使它们成为不可变的结构也是一个好主意。这就是“原始体”的确切含义,这就是不可能从它们继承的原因。您需要一个结构,因为您需要值类型的语义,而不是引用类型的语义。您希望它们是不可变的,因为可变值类型通常不是一个好主意。

暮色呼如

我认为它不能重载,因为C#类都是从Object派生的,因此它们基本上是对象,并且当您使用赋值运算符时,基本上只是在引用另一个对象。另一方面,如果使用结构,则基本上需要所有信息,因此使用=运算符时,将复制所有字段。所以我会说,面对它,并实现一个名为Copy()的函数,您应该没问题:-)
打开App,查看更多内容
随时随地看视频慕课网APP