您好,我需要一些帮助:) 我有自定义类 Filters,在其中定义了显式转换运算符以从 AForge.Point 转换为 System.Drawing.PointF AForge.Point 和 System.Drawing.PointF 都是来自库的结构。 blob.CenterOfGravity 是 AForge.Point 的类型。问题是 intelisense 告诉我“无法将 'AForge.Point' 转换为 'System.Drawing.PointF'。我不知道为什么无法完成此转换:/。感谢所有回复。
class Filters
{
public static explicit operator System.Drawing.PointF(AForge.Point apoint)
{
return new PointF(apoint.X,apoint.Y);
}
public void DrawData(Blob blob, Bitmap bmp)
{
int width = blob.Rectangle.Width;
int height = blob.Rectangle.Height;
int area = blob.Area;
PointF cog = (PointF)blob.CenterOfGravity;
}
...
}
最佳答案
您不能使用运算符
来执行此操作,因为它们必须由您要转换的类型定义(即AForge.Point
或System.Drawing .PointF
)。根据 documentation :
Either the type of the argument to be converted, or the type of the result of the conversion, but not both, must be the containing type.
另一种选择是为 AForge.Point
定义扩展方法:
public static class PointExtensions
{
public static PointF ToPointF(this AForge.Point source)
{
return new PointF(source.X, source.Y);
}
}
并像这样使用:
PointF cog = blob.CenterOfGravity.ToPointF();
关于C# 显式转换运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30152178/