简体   繁体   中英

c# short(=>) operator overloading

I'm successfully overloading operator like this:

public static Vector3D operator +(Vector3D v1, Vector3D v2){
    return new Vector3D(v1._x + v2._x, v1._y + v2._y, v1._z + v2._z);
}

I've read on this page that i could also do it like this:

public static Vector3D operator +(Vector3D v1, Vector3D v2) =>
    new Vector3D(v1._x + v2._x, v1._y + v2._y, v1._z + v2._z);

But in this case, under => I got error saying "; expected". What am I missing?

Looking at the link you have posted the example:

public static Complex operator +(Complex c1, Complex c2) =>  
    new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);  

// Override ToString() to display a complex number   
// in the traditional format:  
public override string ToString() => $"{this.real} + {this.imaginary}";  

strongly suggest that this feature can be applied from the Version of C# 6.0 since also the use of $ as substitute for String.Format exist from the Version of C# 6.0 on and higher.

Try using Visual Studio 2015 to make it work. I did, it worked

Is it possible to update C# version for VS 2012?

Yes, apparently it is. How to do it you will find in this post

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM