[英]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? 如何将浮点型转换为int的方式对结构进行这种类型的行为的受限转换?
Just change the implicit
to explicit
: 只需将implicit
explicit
更改为explicit
implicit
即可:
public static explicit operator Vector2(Complex a)
The implicit
part tells the compiler that it can do it without the code specifying the conversion. implicit
部分告诉编译器无需代码即可指定转换即可完成此操作。 See the Microsoft documentation for user-defined operators for more details. 有关更多详细信息,请参见Microsoft文档中有关用户定义的运算符的信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.