是否可以获取或设置私有字段?
我要去找System.Guid.c
。有没有办法访问它,或者我应该只复制strut中的代码,并将字段公开?
发布于 2012-06-02 21:48:37
你应该试试System.Reflection。下面是一个例子:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace AccessPrivateField
{
class foo
{
public foo(string str)
{
this.str = str;
}
private string str;
public string Get()
{
return this.str;
}
}
class Program
{
static void Main(string[] args)
{
foo bar = new foo("hello");
Console.WriteLine(bar.Get());
typeof(foo).GetField("str", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(bar, "changed");
Console.WriteLine(bar.Get());
//output:
//hello
//changed
}
}
}
发布于 2017-09-29 20:24:53
您可以使用扩展方法来获取任何类型的私有字段:
public static T GetFieldValue<T>(this object obj, string name) {
var field = obj.GetType().GetField(name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
return (T)field?.GetValue(obj);
}
然后访问任意类型的私有字段:
Guid id = Guid.NewGuid();
Int16 c = id.GetFieldValue<Int16>("_c");
发布于 2012-06-02 21:55:35
虽然使用反射可以做到这一点,但简单地从System.Guid.ToByteArray()
检索c
可能会更容易。
byte[] guid = guid.ToByteArray();
short c = (short)((guid[7] << 8) | guid[6]);
由于此方法使用公共的和有文档记录的方法,因此它较少受版本之间的更改的影响。(通常,应该避免依赖私有实现细节,因为这些细节可能会因版本而异。)
https://stackoverflow.com/questions/10862747
复制相似问题