I have 2 types:
- MyImmutableType
- MyDBType
I'd like to introduce a type conversion between the 2 types. I see开发者_如何学Go I can use type conversion with implicit and explicit operators.
My problem is that I don't want to introduce a dependency of MYDBType inside my CommonTypes library. How can I accomplish this? Possibly through extnesion methods? Without having to have my CommonTypes library know about my MyDBType library.
I can do extension methods, but I'm not sure how to do extension operator casts.
Reason: The reason I want to not have a dependency is that I have a client/server architecture. I don't want to distribute my DB class to my client users. But I want my server side code to use a cast easily.
You can't define an implicit or explicit operator anywhere except in one of either of the two classes.
But you can certainly define a conversion method elsewhere, for example in a 3rd library.
The tricky part will be if you want to rely on certain details of one class that are private and therefore need to be handled within the class itself. But if that's the case you really aren't going to have any luck trying to do this without introducing a dependency, unless you want to resort to reflection (a valid alternative in some cases).
As you say, Extensions methods are a really good approach for this. That you you can separate these method in a different class or even a namespace.
I don't think you can really get away from a dependancy here. You can move the conversion to a factory/utility class, that way the types don't have to know about each other. Only the utility class has to have knowledge of both.
精彩评论