简体   繁体   English

声明一个结构符合的接口

[英]Declare an interface that a struct conforms to

I need a PointF-like struct in PCL code. 我需要PCL代码中类似PointF的结构。 But System.Drawing is not available. 但是System.Drawing不可用。 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: 现在,我想定义一个PointF和PointFF都符合的接口IPointF:

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: 最后,我想以某种方式“使其正式化”,使PointF符合IPointF,因此我可以执行以下操作:

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 . 由于您无法控制System.Drawing.PointF ,因此无法说服编译器它实现了IPointF

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

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