进入私人领域私人、领域

2023-09-03 00:47:11 作者:Meyou(蜜友)

是否有可能获取或设置私有字段, 我知道它有点愚蠢的问题,但我想System.Guid.c 那么,有没有一种方法来访问它,或者我应该只是复制了code的支柱,使公共领域?

Is it possible to get or set private fields, I know its a kinda stupid question, but I want to get System.Guid.c So is there a way to access it or should I just copy the code from the strut and make the fields public?

推荐答案

您可以使用反射所建议的Quantic编程

You can use reflection as suggested by Quantic Programming

var guid = Guid.NewGuid();
var field= typeof (Guid).GetField("_c", BindingFlags.NonPublic |BindingFlags.GetField | BindingFlags.Instance);
var value = field.GetValue(guid);

但如果你是好的与第一个转换的GUID为一个字节数组,我会建议:

Although if you are okay with first converting the guid to a byte array, I might suggest:

var guid = Guid.NewGuid();
var c = BitConverter.ToInt16(guid.ToByteArray(), 6);

后一种方法避免使用反射。

The latter approach avoids using reflection.

修改

您需要提要能够设置的值,以及,你还能避免反射:

You mention needing to be able to set the value as well, you can still avoid reflection:

var guid = Guid.NewGuid();
var guidBytes = guid.ToByteArray();

// get value
var c = BitConverter.ToInt16(guidBytes, 6);

// set value
Buffer.BlockCopy(BitConverter.GetBytes(c), 0, guidBytes, 6, sizeof(Int16));
var modifiedGuid = new Guid(guidBytes);
 
精彩推荐
图片推荐