logo
CSharp_Prog_Guide

Результат

A message from the instance method.

A message from the static method.

When to Use Delegates Instead of Interfaces

Both delegates and interfaces enable a class designer to separate type declarations and implementation. A given interface can be inherited and implemented by any class or struct. A delegate can be created for a method on any class, as long as the method fits the method signature for the delegate. An interface reference or a delegate can be used by an object that has no knowledge of the class that implements the interface or delegate method. Given these similarities, when should a class designer use a delegate and when should it use an interface?

Use a delegate in the following circumstances:

Use an interface in the following circumstances:

One good example of using a single-method interface instead of a delegate is IComparable or the generic version, IComparable<(Of <(T>)>). IComparable declares the CompareTo method, which returns an integer that specifies a less than, equal to, or greater than relationship between two objects of the same type. IComparable can be used as the basis of a sort algorithm. Although using a delegate comparison method as the basis of a sort algorithm would be valid, it is not ideal. Because the ability to compare belongs to the class and the comparison algorithm does not change at run time, a single-method interface is ideal.