C# 显式转换运算符

标签 c# explicit-conversion

您好,我需要一些帮助:) 我有自定义类 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.PointSystem.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/

相关文章:

c# - 对象模式的嵌套层次结构

c# - Java 产品甚至可以在没有 JVM 的电脑上运行 - 如何?

c# - 是否可以重载 “as” 或 “is” 运算符

c++ - 为什么这个显式转换运算符适用于 g++ 而不是 Visual Studio 2013?

c++ - 为什么 C++ 隐式转换有效,而显式转换无效?

c# - 适用于 .NET MAUI WebView 的 InMemory HTML 和图像

c# - 使用mysql like语句,输入时自动更新

c# - 基于公司而非用户的复杂领域模型