Announcement

Collapse
No announcement yet.

Hilfreiches für Ereignisse (Null-Check)

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Hilfreiches für Ereignisse (Null-Check)

    [Edit=gfoidl] Abgeteilt von eigene event erstellen [/url]

    Hallo,

    da wir schon bei Events sind schreibe ich mal 2 "Tricks" damit der Umgang mit dem Null-Check einfacher wird.
    1. Der immer selbe Check kann in eine Erweiterungsmethode verpackt werden.
      [highlight=c#]
      public static class EventExtensions
      {
      public static void Fire(this EventHandler handler, object sender)
      {
      if (handler != null)
      handler(sender, EventArgs.Empty);
      }

      public static void Fire<T>(this EventHandler<T> handler, object sender, T eventArgs)
      where T : EventArgs
      {
      if (handler != null)
      handler(sender, eventArgs);
      }
      }

      public class Foo
      {
      public event EventHandler MyFooEvent;

      public void DoSomething()
      {
      this.MyFooEvent.Fire(this);
      }
      }
      [/highlight]
    2. Der Null Check kann durch das Zuweisen eines (sinnlosen) Delegaten ganz entfernt werden.
      [highlight=c#]
      public class Foo
      {
      public event EventHandler MyFooEvent = delegate { };

      public void DoSomething()
      {
      this.MyFooEvent(this, EventArgs.Empty);
      }
      }
      [/highlight]


    Funktioniert wunderbar


    mfG Gü
    Zuletzt editiert von gfoidl; 14.09.2010, 16:45.
    "Any fool can write code that a computer can understand. Good programmers write code that humans can understand". - Martin Fowler

  • #2
    Natürlich gaaaaaaanz unabhängig von einem aktuellen Thread den ich hier jetzt namentlich nicht erwähnen will. Aber trotzdem eine wirklich gute Idee. Boah und auch gleich noch als extension Method. Sehr nett. Das werd ich bestimmt auch das ein oder andere mal benutzen.

    Haste das auch aus deinen Bookmarks? (kleiner Insider)

    Comment


    • #3
      Hallo Florian,

      Haste das auch aus deinen Bookmarks?
      Nein, irgendwas hab ich im Kopf auch
      Edit: Da hab ich nicht nur eine Schnur welche die Ohren an ihrer Position hält


      mfG Gü
      "Any fool can write code that a computer can understand. Good programmers write code that humans can understand". - Martin Fowler

      Comment


      • #4
        Hab mir auch schon oft drüber Gedanken gemacht, dass das ganze etwas redundant und nervig ist. Und das mit NULL Checks sehr schön mit extension methods machen kann ist mir auch bewusst. Aber irgendwie bin ich da noch nie drauf gekommen Aber ist wirklich sehr sehr praktisch. Total genial find ich auch extension methods auf Interfaces. Da spart man sich sehr oft die abstrakten Klassen und die Vererbung.

        Comment


        • #5
          Hallo,

          Total genial find ich auch extension methods auf Interfaces
          Linq sei Dank

          Da kann ich dir zustimmen. Das ermöglicht ganz praktische Dinge und der Code wird mMn auch leserlicher.
          Ich weiß dass dir das klar ist, aber für die Nachwelt ein einfacher Vergleich
          [highlight=c#]
          Console.WriteLine(StringHelper.Reverse(myString));

          // gegen

          Console.WriteLine(myString.Reverse());
          [/highlight]


          mfG Gü
          "Any fool can write code that a computer can understand. Good programmers write code that humans can understand". - Martin Fowler

          Comment


          • #6
            Naja mir gehts nicht nur eben mal um Framework Klassen, sondern auch für selbstgebaute. Man nehme z.B. ein Interface um irgendwas über einen Übertragungskanal zu schicken (später z.B. SerialPort oder TCP/IP)

            [highlight=c#]
            public interface ICommunicationChannel
            {
            void Write(byte[] bytesToWrite);
            }
            [/highlight]

            Ein ganz einfaches Interface. So nun möchte man aber evtl. ein paar Komfortfunktionen programmieren. Zum Beispiel möchte man einzelne Bytes senden oder einen String der ASCII kodiert wird. Der Klassische Weg wäre z.B. eine abstrakte Basisklasse. Noch dazu müsste ich die Funktionen direkt ins Interface aufnehmen.

            [highlight=c#]
            public interface IComfortCommunicationChannel: ICommunicationChannel
            {
            void Write(Byte byteToWrite);
            void Write(String stringToWrite);
            }

            public abstract class BaseCommunicationChannel: IComfortCommunicationChannel
            {
            public abstract void Write(byte[] bytesToWrite);

            public void Write(byte byteToWrite)
            {
            Write(new [] { byteToWrite });
            }

            public void Write(String stringToWrite)
            {
            var enc = new AsciiEncoding();

            Write(enc.GetBytes(stringToWrite));
            }
            }
            [/highlight]

            Das wäre ein Möglichkeit. Die andere wäre eine extra Komfortklasse die einen ICommunicationChannel bekommt und die Funktionalität bietet:

            [highlight=c#]
            public class ComfortCommunicationChannel:IComfortCommunicationC hannel
            {
            private ICommunicationChannel _communicationChannel;

            public ComfortCommunicationChannel(ICommunicationChannel communicationChannel)
            {
            _communicationChannel = communicationChannel;
            }

            public void Write(byte[] bytesToWrite)
            {
            _communicationChannel.Write(bytesToWrite);
            }

            public void Write(byte byteToWrite)
            {
            _communicationChannel.Write(new [] { byteToWrite } );
            }

            public void Write(String stringToWrite)
            {
            var enc = new AsciiEncoding();
            _communicationChannel.Write(enc.GetBytes(stringToW rite));
            }
            }
            [/highlight]

            Könnte man auch noch machen, allerdings muss man dann schon 2 Klassen instanziieren bzw. konfigurieren.

            Über Extension Methods kann ich die Funktionalität aber schon auf Interface Ebene implementieren und jede Klasse die das Interface implementiert kann die Funktionen sofort verwenden:

            [highlight=c#]
            public static class CommunicationChannelExtensions
            {
            public static void Write(this ICommunicationChannel communicationChannel, byte byteToWrite)
            {
            communicationChannel.Write(new [] { byteToWrite } );
            }

            public static void Write(this ICommunicationChannel communicationChannel, String stringToWrite)
            {
            var enc = new AsciiEncoding();
            communicationChannel.Write(enc.GetBytes(stringToWr ite));
            }
            }
            [/highlight]

            Finde ich persönlich sehr genial. Man hat ein minimales Interface und kann trotzdem schon Funktionalität hinzufügen.

            Comment

            Working...
            X