为什么下面的代码不起作用:
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;
}
}
}
我正在尝试设置私有(private)字段的值。
这是我得到的异常:
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:\Users\Antonio\Desktop\ConsoleApplication7\ConsoleApplication7\Program.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:
最佳答案
试试这个(灵感来自 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
。
关于c# - 设置私有(private)字段的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12993962/