加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 设置私有域的值

发布时间:2020-12-15 06:47:33 所属栏目:百科 来源:网络整理
导读:为什么以下代码不工作: 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... .
为什么以下代码不工作:
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:

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,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方法 – 您正在访问一个字段而不是一个属性,以及使用NonPublic与Instance.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读