扩展一个类使其成为可转换的

Moo*_*eef 1 c# xna

我想扩展一个类(Vector2),使其可以转换为Point.我怎么做?

部分问题:

  1. 扩展课程
  2. 将类转换为另一个类

最后我希望能够做到这一点:

Vector2 foo = new Vector2(5.2f);  // X = 5.2f Y = 5.2F
Point red = new Point(2,2);  // X = 2 Y = 2
red = foo;  // I know that you can make classes convert themselves automatically... somehow?
// Now red.X = 5 red.Y = 5
Run Code Online (Sandbox Code Playgroud)

Ler*_*eri 12

你不能这样做.

Vector2是一个struct,而不是一个class.而且你知道它是不可能派生出来的,struct因为结构在堆栈上分配固定大小.因此,多态性是不可能的,因为派生的struct大小不同.

作为一种解决方法,您可以创建将返回struct实例的扩展方法 :ToPointPoint

public static class Extensions {
    public static void ToPoint(this Vector2 vector) {
        return new Point((int)vector.X, (int)vector.Y);
    }
}

//Usage:
Vector2 foo = new Vector2(5.2f);//X = 5.2f Y = 5.2F
Point red = foo.ToPoint();
Run Code Online (Sandbox Code Playgroud)

注意:这种方式比将向量隐式转换为点更直观,因为向量不是一个点.隐式演员在这些类型之间没有任何意义.实际上,隐式转换非常有用的情况很少.