简体   繁体   中英

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.

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:

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).

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