要使用指针,您必须使用不安全的代码。但是您可以使用移位和位运算符来实现您想要的。
// attempt to read individual bytes of an int
int r = (color & 0x00FF0000)>>16;
int g = (color & 0x0000FF00)>>8;
int b = (color & 0x000000FF);
Console.WriteLine("R-{0:X}, G-{1:X}, B-{2:X}", r, g, b);
// attempt to modify individual bytes of an int
int r1 = 0x1A;
int g1 = 0x2B;
int b1 = 0x3C;
color = (color & ~0x00FF0000) | r1 << 16;
color = (color & ~0x0000FF00) | g1 << 8;
color = (color & ~0x000000FF) | b1;
Console.WriteLine("Color-{0:X}", color);
您可以根据需要将此片段包装在结构中。
这是不安全代码的解决方案,您必须在构建选项中设置允许不安全代码。
using System;
namespace PixelTest
{
public unsafe struct Pixel
{
private int _color;
public Pixel(int color)
{
_color = color;
}
public int GetColor()
{
return _color;
}
public int GetR()
{
fixed(int* c = &_color)
{
return *((byte*)c + 2);
}
}
public int GetG()
{
fixed(int* c = &_color)
{
return *((byte*)c + 1);
}
}
public int GetB()
{
fixed(int* c = &_color)
{
return *(byte*)c;
}
}
public void SetR(byte red)
{
fixed (int* c = &_color)
{
*((byte*)c + 2) = red;
}
}
public void SetG(byte green)
{
fixed (int* c = &_color)
{
*((byte*)c + 1) = green;
}
}
public void SetB(byte blue)
{
fixed (int* c = &_color)
{
*(byte*)c = blue;
}
}
}
class Program
{
static void Main(string[] args)
{
Pixel c = new Pixel(0xFFAABB);
Console.WriteLine("R-{0:X}, G-{1:X}, B-{2:X}", c.GetR(), c.GetG(), c.GetB());
c.SetR(0x1A);
c.SetG(0x2B);
c.SetB(0x3D);
Console.WriteLine("Color - {0:X}", c.GetColor());
}
}
}