Csharp/CSharp Tutorial/Reflection/Property

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Get/set a property using a PropertyInfo

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);
        
             //get and set a property using a PropertyInfo
         PropertyInfo property = type.GetProperty("Text");
         property.SetValue(o, "www.softconcepts.ru", null);
         string text = (string)property.GetValue(o, null);
        
         Console.WriteLine(text);
        
         EventInfo eventInfo = type.GetEvent("Changed");
         eventInfo.AddEventHandler(o, new EventHandler(Class1.OnChanged));
             ((MyClass)o).Text = "New Value";
      }
      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;
  }

List Properties

using System;
using System.Reflection;
public interface IFaceOne
{
  void MethodA();
}
public interface IFaceTwo
{
  void MethodB();
}
public class MyClass: IFaceOne, IFaceTwo
{
  public enum MyNestedEnum{}
  
  public int myIntField;
  public string myStringField;
  public void myMethod(int p1, string p2)
  {
  }
  public int MyProp
  {
    get { return myIntField; }
    set { myIntField = value; }
  }
  void IFaceOne.MethodA(){}
  void IFaceTwo.MethodB(){}
}
public class MainClass
{
  public static void Main(string[] args)
  {
    MyClass f = new MyClass();
       Type t = f.GetType();
    PropertyInfo[] pi = t.GetProperties();
    foreach(PropertyInfo prop in pi)
      Console.WriteLine("Prop: {0}",  prop.Name);
  }
}
Prop: MyProp

Using Type.GetProperties() to Obtain an Object"s Public Properties

using System;
class MainClass
{
  static void Main()
  {
    DateTime dateTime = new DateTime();
    
    Type type = dateTime.GetType();
    foreach (
        System.Reflection.PropertyInfo property in
            type.GetProperties())
    {
        System.Console.WriteLine(property.Name);
    }
  }
}