重载二进制struct运算符

时间:2015-02-10 09:40:30

标签: c# arrays struct overloading

我一直在寻求解决我在论坛内外的困境,但我什么也没找到。因此,我会向你提出我的问题,希望得到一个建议。

我正在构建一个必须使用字节数组表示图像(位图)的结构。我发现没有什么能快速有用地满足我的需求。

public struct image
    {
    BitmapData bmd;
    byte[] x;
    unsafe byte*[] xy;
    }

其中xy数组应该只是一个指针数组,允许xy [4] [5]技巧访问第4行的第5个字节。

除了几个构造函数

image(ref Bitmap tbm)
{
    bmd = tbm.LockBits(new Rectangle(0, 0, tbm.Width, tbm.Height), ImageLockMode.ReadWrite, tbm.PixelFormat);
    x = new byte[bmd.Stride * bmd.Height];
    Marshal.Copy(bmd.Scan0, x, 0, bmd.Stride * bmd.Height);
    unsafe
    {
        xy = new byte*[bmd.Height];
        xy[0] = (byte*)bmd.Scan0;
    for (int i = 0; i < bmd.Height; i++) { xy[i] = xy[0] + i * bmd.Stride; }
    }
}

image(ref image tx)
    {
    bmd = tx.bmd;
    x = new byte[tx.size()];
    tx.x.CopyTo(x,0);
    unsafe { xy = new byte*[tx.bmd.Height];  tx.xy.CopyTo(xy, 0); }
    }

我想添加一个用户友好的运算符 通过引用将一个图像复制到另一个图像。 与第二个构造函数类似,它不是两个数组的新副本,而只是像这样的

void linkTo(ref image source)
    {
    this.bmd = source.bmd;
    this.x = source.x;
    unsafe { this.xy = source.xy; }
    }

或者更喜欢这个

static void link(ref image i1,ref image i2)
    {
    i1.bmd = i2.bmd;
    i1.x = i2.x;
    unsafe { i1.xy = i2.xy; }
    }

由于无法覆盖(或重载?)=运算符既不创建新的运算符&lt; = 8我试图以这种方式重载shift运算符:

public static void operator <<(ref image i1,ref image i2)
    {
    i1.bmd = i2.bmd;
    i1.x = i2.x;
    unsafe { i1.xy = i2.xy; }
    }
由于void返回类型, piteously失败 ,可能因为我错过了一些关于重载的问题。

我想要做的是使用运算符

myImage1 << myImage2;

创建myImage2到myImage1的引用副本,以允许使用myImage1(例如)编辑myImage2。

类似于

的东西
myImage1.linkTo(ref myImage2)

image.link(ref myImage1,ref myImage2)

之前的例子。

我的问题是: 如何创建或超载运营商以执行上述操作? 我的代码中是否有明显的错误?

感谢您的关注!

0 个答案:

没有答案
相关问题