简体   繁体   中英

Custom struct with casting to another type in C#

I have a struct currently that i can cast to another type like this:

    public static implicit operator Vector2(Complex a)
    {
        return new Vector2(a.Real,a.Imaginary);
    }

At the moment how ever this is allowed automatically:

Vector2 a = new Complex(b,c); //valid

But i would prefer it did not automatically allow this. But rather only allow:

Vector2 a = (Vector2) new Complex(b,c);

How can i have a restricted casting with this kinda behaviour for my struct the same way floats casting to ints work?

Just change the implicit to explicit :

public static explicit operator Vector2(Complex a)

The implicit part tells the compiler that it can do it without the code specifying the conversion. See the Microsoft documentation for user-defined operators for more details.

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