在C中,我们可以通过以下方式访问guid的成员:
GUID guid = {0};
CoCreateGuid(&guid);
dwRand = guid.Data1 & 0x7FFFFFFF;
C中guid的结构是:
Data 1 - unsigned long
Data 2 - unsigned short
Data 3 - unsigned short
Data 4 - unsigned char
问题:如何翻译C代码中的第三行(dwRand = guid.Data1& 0x7FFFFFFF;).换句话说 – 如何访问guid成员?在C#中没有这样的东西.
提前致谢!
解决方法:
您可以创建一个结构:
public struct MyGuid
{
public int Data1;
public short Data2;
public short Data3;
public byte[] Data4;
public MyGuid(Guid g)
{
byte[] gBytes = g.ToByteArray();
Data1 = BitConverter.ToInt32(gBytes, 0);
Data2 = BitConverter.ToInt16(gBytes, 4);
Data3 = BitConverter.ToInt16(gBytes, 6);
Data4 = new Byte[8];
Buffer.BlockCopy(gBytes, 8, Data4, 0, 8);
}
public Guid ToGuid()
{
return new Guid(Data1, Data2, Data3, Data4);
}
}
现在,如果你想修改一个Guid:
Guid g = GetGuidFromSomewhere();
MyGuid mg = new MyGuid(g);
mg.Data1 &= 0x7FFFFFFF;
g = mg.ToGuid();