设置私有字段的值

时间:2012-10-21 00:44:33

标签: 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;
        }
    }   
}

我正在尝试设置私有字段的值。


这是我得到的例外:

  

System.NullReferenceException未处理Message = Object引用   未设置为对象的实例。来源= ConsoleApplication7
  堆栈跟踪:          在C:\ Users \ Antonio \ Desktop \ ConsoleApplication7 \ ConsoleApplication7 \ Program.cs中的Program.Main(String [] args):行   18          在System.AppDomain._nExecuteAssembly(RuntimeAssembly程序集,String [] args)          在System.AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args)          在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()          在System.Threading.ThreadHelper.ThreadStart_Context(对象状态)          at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean   ignoreSyncCtx)          在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态)          在System.Threading.ThreadHelper.ThreadStart()InnerException:

2 个答案:

答案 0 :(得分:59)

试试这个(受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

答案 1 :(得分:1)

显然,添加BindingFlags.Instance似乎解决了这个问题:

> 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]
>