C# 显式转换运算符
C# explicit conversion operators
你好,我需要一些帮助:)
我有我的自定义 class 过滤器,我在其中定义了显式转换运算符以从 AForge.Point 转换为 System.Drawing.PointF AForge.Point 和 System.Drawing.PointF 都是来自库的结构。 blob.CenterOfGravity 是 AForge.Point 的类型。问题是智能感知告诉我“无法将 '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;
}
...
}
您不能使用 operator
执行此操作,因为它们必须由您正在转换的类型定义(即 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();
你可以试试这个
private static System.Drawing.PointF convertToPointF(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 = convertToPointF(blob.CenterOfGravity);
}
你好,我需要一些帮助:) 我有我的自定义 class 过滤器,我在其中定义了显式转换运算符以从 AForge.Point 转换为 System.Drawing.PointF AForge.Point 和 System.Drawing.PointF 都是来自库的结构。 blob.CenterOfGravity 是 AForge.Point 的类型。问题是智能感知告诉我“无法将 '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;
}
...
}
您不能使用 operator
执行此操作,因为它们必须由您正在转换的类型定义(即 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();
你可以试试这个
private static System.Drawing.PointF convertToPointF(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 = convertToPointF(blob.CenterOfGravity);
}