进入私人领域 [英] Access private fields

查看:169
本文介绍了进入私人领域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能获取或设置私有字段,
我知道它有点愚蠢的问题,但我想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);

这篇关于进入私人领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆