开发者

C# adding implict conversions to existing types

Is there a way in C# to add implicit conversions to types already defined in other assemblies?

For example, if I am using开发者_JAVA技巧 two different assemblies which each provide their own Vector3 struct, and use it in their APIs, it would be nice to be able to define a conversion once, and then just pass a Foo.Vector3 to a method that expects a Bar.Vector3, and have it automatically converted.

If I had the source for the libraries then I could add implicit conversion operators. Without that source, I am currently doing the conversion explicitly myself with a helper function every time. I'm hoping for a nicer way.

I realize I could create my own Vector3 struct with implicit conversion operators to and from the other two structs, but this wouldn't solve all the cases where I want to directly pass an object of one (externally defined) type to a method expecting the other.

Bonus question: is there anything authors of libraries that expose things like a Vector3 struct in their API should do to facilitate ease of use in this regard?


You can provide implicit conversion to-and-from a third-party type for any type that you author yourself, but you cannot add support for implicit conversion between two third-party types.

You could improve the elegance of converting between the two types somewhat by adding extension methods to both Vector3 types;

public static Bar.Vector3 ToBarVector3(this Foo.Vector3 foo) {
    return /* instance of Bar.Vector3 */
}

public static Foo.Vector3 ToFooVector3(this Bar.Vector3 bar) {
    return /* instance of Foo.Vector3 */
}

That's about the best you can expect to achieve.


Unfortunately you cannot add implicit conversions that convert to and from a type that you cannot change. I would have recommended the workaround you mentioned, but you already mentioned it :).

I’m afraid even the answer to your bonus question is “you can’t”.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜