简体   繁体   English

自定义日期类型到双精度类型的转换

[英]custom Date type to double type conversion

If I have a custom date type called MyDate in which I have written operators for implicit conversion of double and MyDate to each other. 如果我有一个称为MyDate的自定义日期类型,其中我编写了用于将double和MyDate彼此隐式转换的运算符。

My question: is there any way to switch this implicit conversion off for a particular method parameter ? 我的问题:是否可以针对特定方法参数关闭此隐式转换? is that a good idea at all? 那是个好主意吗?

eg 例如

public class A {
    ...

    public void AMethod(double x, double y) {

      // do something
    }
}

I don't want in the particular case of AMethod() for someone to be able to call it like this: 我不希望在AMethod()的特殊情况下有人可以像这样调用它:

A a = new A();
a.AMethod(m, n);  // m and n are of type MyDate

I don't think it is possible to switch off implicit conversions for selected methods only, either you get all of them or nothing. 我认为不可能只为选定的方法关闭隐式转换,要么获得所有转换,要么一无所获。

Having said that, implicit conversions should only be implemented if you don't loose anything while doing the conversion, eg you should not care if the conversion occurred or not. 话虽如此,隐式转换仅应在执行转换时不松动任何内容的情况下实现,例如,您不必在意转换是否发生。 If this is not the case (or if this is not the case in one direction at least), then change the implicit conversions to explicit and your issue with disappear. 如果不是这种情况(或者至少在一个方向上不是这种情况),则将隐式转换更改为显式,然后您的问题消失。 Of course your code will be more explicit with all these conversions, but rightly so. 当然,通过所有这些转换,您的代码将更加明确,但是正确的是。

It is not a good idea. 这不是一个好主意。 When you create your custom implicit conversions you should implement it in such a way that it is applicable in all possible scenarios. 创建自定义隐式转换时,应以适用于所有可能情况的方式实施它。 The possibility to switch it off in certain scenarios would make the code harder to read and could potentially introduce bugs. 在某些情况下关闭它的可能性将使代码更难阅读,并可能引入错误。

If you want to have the possibility to switch the conversion on and off you should simply implement the explicit conversion (which you can then apply when needed). 如果希望有可能打开和关闭转换,则只需实现显式转换(然后可以在需要时应用即可)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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