设置私有字段的值 [英] 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.
这是我得到的例外:
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:
推荐答案
试试这个(灵感来自 使用 Reflection 查找私有字段?):
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");
我的更改是使用 GetField
方法 - 您正在访问字段而不是属性,并且使用 Instance
或 NonPublic
.
My changes were to use the GetField
method - you are accessing a field and not a property, and to or NonPublic
with Instance
.
这篇关于设置私有字段的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文