简体   繁体   中英

Declare an interface that a struct conforms to

I need a PointF-like struct in PCL code. But System.Drawing is not available. So I declare my own struct:

public struct PointFF: IPointF {
  public float X { get; set; };
  public float Y { get; set; };
}

Now I want to define an interface IPointF that both PointF and PointFF conform to:

interface IPointF {
  float X {get; set; };
  float Y {get; set; };
}

Lastly, I want to somehow "make it official" that PointF conforms to IPointF, so I can do things like this:

public void DoFunkyStuff (IPointF p) {
  float x = p.X;
  float y = p.Y;
  // do something with x and y
}

Is that possible?

No, it's no possible for you do to what you want.

In general, though it is possible for structures to implement interfaces, it's considered a very bad idea. It forces your structures to be boxed, and tends to break the value-type semantics you expect from a structure. But the language permits it, so that's not your main problem.

What you can't do is to somehow arrange from a pre-existing structure to implement that interface without changing it's source code. Since you have no control over System.Drawing.PointF , there's nothing you can do to convince the compiler that it implements your IPointF .

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