设置私有字段的值
为什么以下代码不起作用:
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; } } }
我正在尝试设置私有字段的值。
这是我得到的例外:
System.NullReferenceException未处理Message = Object引用未设置为对象的实例。 来源= ConsoleApplication7
StackTrace:位于C: Users Antonio Desktop ConsoleApplication7 ConsoleApplication7 Program.cs中的Program.Main(String [] args):位于System的System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly,String [] args)的第18行。 System.Threading.ExecutionContext.Run上的System.Threading.ThreadHelper.ThreadStart_Context(Object state)中的Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()中的AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args)(ExecutionContext executionContext System.Threading.ThreadHelper.ThreadStart()中的System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态),ContextExallback回调,对象状态,布尔值ignoreSyncCtx:InnerException:
尝试这个(灵感来自使用Reflection查找私有字段? ):
var prop = s.GetType().GetField("id", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); prop.SetValue(s, "new value");
我的更改是使用GetField
方法 – 您正在访问字段而不是属性,以及使用Instance
NonPublic
。
显然,添加BindingFlags.Instance
似乎解决了它:
上述就是C#学习教程:设置私有字段的值分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
> 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] >
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/942403.html