简体   繁体   中英

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) : this(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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM