简体   繁体   中英

C# explicit conversion operators

Hello I need some help :) I have my custom class Filters and inside of it I defined explicit conversion operator to convert from AForge.Point to System.Drawing.PointF both AForge.Point and System.Drawing.PointF are structs from libraries. blob.CenterOfGravity is type of AForge.Point. The problem is that intelisense is telling me that "Cannot convert 'AForge.Point' to 'System.Drawing.PointF'. I don't know why this conversion can't be done :/. Thanks for all replies.

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;
        }
        ...
}

You can't do this using an operator as these have to be defined by the types you are converting (ie AForge.Point or System.Drawing.PointF ). Per the 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.

One alternative is to define an extension method for AForge.Point :

public static class PointExtensions
{
    public static PointF ToPointF(this AForge.Point source)
    {
        return new PointF(source.X, source.Y);
    }
}

And use like this:

PointF cog = blob.CenterOfGravity.ToPointF();

U could try this

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);
    }

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