简体   繁体   English

C#PointF减去?

[英]C# PointF Subtract?

Was a bit shocked to discover that System.Drawing.PointF appears to have operators for subtracting sizes but not other PointFs. 惊讶地发现System.Drawing.PointF似乎具有用于减去大小的运算符,但没有其他PointF。 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. 因此,我尝试编写自己的PointF类,但是它需要能够将System.Drawing.Points自动转换为它,否则它实际上并没有增加任何便利。 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' 无法从“ System.Drawing.Point”转换为“ my_namespace.PointF”

(I have a function that accepts a my_namespace.PointF but I'm passing in a System.Drawing.Point ). (我有一个接受my_namespace.PointF的函数,但我正在传递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? 您在my_namespace.PointF类中定义了隐式转换吗? 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. 您本身不能通过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. 方法(在框架的下一个修订版中提出)..但是您应该能够对+使用一个名为Add()的同义词方法并获得。

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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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