设置私有字段的值

Ton*_*Nam 30 c# reflection

为什么以下代码不起作用:

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;
        }
    }   
}
Run Code Online (Sandbox Code Playgroud)

我试图设置私有字段的值.


这是我得到的例外:

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:

nic*_*k_w 69

尝试这个(灵感来自使用Reflection查找私有字段?):

var prop = s.GetType().GetField("id", System.Reflection.BindingFlags.NonPublic
    | System.Reflection.BindingFlags.Instance);
prop.SetValue(s, "new value");
Run Code Online (Sandbox Code Playgroud)

我的改变是使用GetField方法-你正在访问一个领域,而不是财产,或NonPublicInstance.

  • 根据 Jon Skeet 的说法,设置结构的正确方法需要在调用 SetValue 之前进行显式装箱:/sf/ask/439635451/ -使用反射 (2认同)