Can I add an implicit conversion for two classes which I don't directly control?

后端 未结 2 1280
粉色の甜心
粉色の甜心 2020-12-17 14:56

I\'d like to be able to implicitly convert between two classes which are otherwise incompatible.

One of the classes is Microsoft.Xna.Framework.Vector3,

相关标签:
2条回答
  • 2020-12-17 15:45

    In C# you cannot. You could provide descendant types that have the extra conversions (provided the types aren't sealed); Or you could provide a generic wrapper class that somehow adds the conversion.

    The convenience of all this depends on the way in which these wrappers/adaptations can be used with the original APIs.

    On another note I see you are useing F# as well. IIRC F# is supposed to have some level of meta-programming ability (like many functional languages for .NET, such as Boo and Nemerle). It would not surprise me if that could be used here. Unfortunately my F is not sharp enough to help there

    0 讨论(0)
  • 2020-12-17 15:48

    No, you can't. The implicit operator has to be defined as a member of one of the classes. However, you can define an extension method (your example didn't work as extension methods have to be in a public static class).

    public static class ConverterExtensions
    {
        public static Vector ToVector (this Vector3 input)
        {
          //convert
        }
    }
    
    0 讨论(0)
提交回复
热议问题