Re[2]: А еще можно так... :)
От: desco США http://v2matveev.blogspot.com
Дата: 04.10.06 07:27
Оценка:
Здравствуйте, ppti, Вы писали:

В случае, если мы имеем дело с field-like events, можно поступить так, как здесь
Автор: _FRED_
Дата: 03.10.06
предложил _FRED_, только используя рефлекшн

  class TestClass
  {
    public static event EventHandler StaticEvent;
    public event EventHandler InstanceEvent;
    
    static public void RaiseStaticEvent()
    {
      if (StaticEvent != null)
      {
        StaticEvent(null, EventArgs.Empty);
      }
      else
      {
        Console.WriteLine("Empty invocation list");
      }
    }

    public void RaiseInstanceEvent()
    {
      if (InstanceEvent != null)
      {
        InstanceEvent(null, EventArgs.Empty);
      }
      else
      {
        Console.WriteLine("Empty invocation list");
      }
    }    
    
    public static void RemoveAllEvents(object instance, EventInfo eventInfo)
    {
      Type rt = instance != null ? instance.GetType() : eventInfo.ReflectedType;
      BindingFlags bf = BindingFlags.NonPublic;
      bf |= instance != null ? BindingFlags.Instance : BindingFlags.Static;
      FieldInfo fi = rt.GetField(eventInfo.Name, bf);
      if (fi != null)
      {
        fi.SetValue(instance, null);
      }      
    }
  }

  public class Program
  {
    static void Main(string[] args)
    {
      TestClass.StaticEvent += delegate
                                 {
                                   Console.WriteLine("Static event");
                                 };
      TestClass instance = new TestClass();
      instance.InstanceEvent += delegate
                                  {
                                    Console.WriteLine("Instance event");
                                  };
      
      TestClass.RaiseStaticEvent();
      instance.RaiseInstanceEvent();
      
      TestClass.RemoveAllEvents(null, typeof(TestClass).GetEvent("StaticEvent"));
      TestClass.RemoveAllEvents(instance, typeof(TestClass).GetEvent("InstanceEvent"));

      TestClass.RaiseStaticEvent();
      instance.RaiseInstanceEvent();
      
    }
  }



вывод:

Static event
Instance event
Empty invocation list
Empty invocation list

 
Подождите ...
Wait...
Пока на собственное сообщение не было ответов, его можно удалить.