开发者

C# PointF Subtract?

Was a bit shocked to discover that System.Drawing.PointF appears to have operators for subtracting sizes but not other PointFs. So I'm trying to write my own PointF class, but it needs to be able to have System.Drawing.Points automatically converted to it, or it really doesn't add any convenience. So I wrote these constructors:

    public PointF(float x = 0, float y = 0)
    {
        this.x = x;
        this.y = y;
    }

    public PointF(System.Drawing.PointF p) : t开发者_JS百科his(p.X, p.Y) { }
    public PointF(System.Drawing.Point p) : this(p.X, p.Y) { }

But I'm still getting this error:

cannot convert from 'System.Drawing.Point' to 'my_namespace.PointF'

(I have a function that accepts a my_namespace.PointF but I'm passing in a System.Drawing.Point).

Shouldn't the 3rd constructor kick in and auto-convert it?


Do you have an implicit conversion defined in your my_namespace.PointF class? It won't automatically convert otherwise.

public PointF(float x = 0, float y = 0)
{
    this.x = x;
    this.y = y;
}

public PointF(System.Drawing.PointF p) : this(p.X, p.Y) { }
public PointF(System.Drawing.Point p) : this(p.X, p.Y) { }

//add this:
public static implicit operator PointF(System.Drawing.Point pt) 
{ return new PointF(pt); }


Have you considered the option of writing an 'extension method' instead of rolling out your own class ?

You can't have operator overloading per se via extn. methods (proposed in next revision of the framework).. but you should be able to use a synonymous method called Add() for + and get by.


This compiles for me:

class PointF {
 float x; float y;
 public PointF(float x, float y)
 {
     this.x = x;
     this.y = y;
 }

 public PointF(System.Drawing.PointF p) : this(p.X, p.Y) { }
 public PointF(System.Drawing.Point p) : this(p.X, p.Y) { }

 public static implicit operator PointF(System.Drawing.Point pt) { return new PointF(pt); }
 public static implicit operator PointF(System.Drawing.PointF pt) { return new PointF(pt); }
}
//....
static void test(pointf.PointF p) {
}
//....
test(new System.Drawing.PointF(1, 1));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜