Get/set a field using a FieldInfo : Field « Reflection « C# / CSharp Tutorial






using System;
using System.Reflection;
using System.Windows.Forms; 

  public class Class1
  {
      static void Main( string[] args )
      {
        Type type = typeof(MyClass);
        object o = Activator.CreateInstance(type);
      
             FieldInfo field = type.GetField("text", BindingFlags.NonPublic | BindingFlags.Instance);
             field.SetValue(o, "www.domain.com");
             string text = (string)field.GetValue(o);
        
             Console.WriteLine(text);
        
      }
      private static void OnChanged(object sender , System.EventArgs e)
      {
        Console.WriteLine(((MyClass)sender).Text);
      }
  }
  public class MyClass
  {
    private string text;
    
    public string Text
    {
      get{ return text; }
      set
      { 
        text = value;
        OnChanged(); 
      }
    }
    
    private void OnChanged()
    {
      if( Changed != null )
        Changed(this, System.EventArgs.Empty); 
    }
    
    public event EventHandler Changed;
  }








19.4.Field
19.4.1.Get all fields from a Type
19.4.2.List Fields
19.4.3.Deeper Reflection: iterate through the fields of the class
19.4.4.Get/set a field using a FieldInfo
19.4.5.Reflecting On Members Of A Type
19.4.6.Get Type full name and base type and its members