Set value of private field
Why is the following code not working:
class Program
{
static void Main ( string[ ] args )
{
SomeClass s = new SomeClass( );
s.GetType( ).GetField( "id" , System.Reflection.BindingFlags.NonPublic ) // sorry reasently updated to GetField from GetProperty...
.SetValue( s , "new value" );
}
}
class SomeClass
{
object id;
public object Id
{
get
{
return id;
}
}
}
I am trying to set the value of a private field.
Here is the exeption I get:
System.NullReferenceException was unhandled Message=Object reference not set to an instance of an object. Source=ConsoleApplication7
StackTrace: at Program.Main(String[] args) in C:UsersAntonioDesktopConsoleApplication7ConsoleApplication7Program.cs:line 18 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException:
Try this (inspired by Find a private field with Reflection?):
var prop = s.GetType().GetField("id", System.Reflection.BindingFlags.NonPublic
| System.Reflection.BindingFlags.Instance);
prop.SetValue(s, "new value");
My changes were to use the GetField
method - you are accessing a field and not a property, and to or NonPublic
with Instance
.
显然,添加BindingFlags.Instance
似乎已经解决了它:
> class SomeClass
{
object id;
public object Id
{
get
{
return id;
}
}
}
> var t = typeof(SomeClass)
;
> t
[Submission#1+SomeClass]
> t.GetField("id")
null
> t.GetField("id", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
> t.GetField("id", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)
[System.Object id]
>
链接地址: http://www.djcxy.com/p/95936.html
上一篇: 使用WMI和C#获取MSMQ队列
下一篇: 设定私人领域的价值