Set value of private field

后端 未结 2 505
执念已碎
执念已碎 2020-12-13 17:56

Why is the following code not working:

class Program
{
    static void Main ( string[ ] args )
    {
        SomeClass         


        
相关标签:
2条回答
  • 2020-12-13 18:36

    Try this (inspired by 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");
    

    My changes were to use the GetField method - you are accessing a field and not a property, and to or NonPublic with Instance.

    0 讨论(0)
  • 2020-12-13 18:49

    Evidently, adding BindingFlags.Instance seems to have solved it:

    > 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]
    > 
    
    0 讨论(0)
提交回复
热议问题