c# – 设置私有域的值
为什么以下代码不工作:
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; } } } 我正在设置一个私有字段的值. 这是我得到的exeption:
解决方法
尝试这个(灵感来自
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方法 – 您正在访问一个字段而不是一个属性,以及使用NonPublic与Instance. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |