Generic Interfaces


Using generics you can define interfaces that define methods with generic parameters. In the linked list sample, you’ve already implemented the interface IEnumerable<T> , which defines a GetEnumerator() method to return IEnumerator<T>. For many nongeneric interfaces of .NET 1.0, new generic versions have been defined since .NET 2.0, for example IComparable<T>:

  public interface IComparable<T> {    int CompareTo(T other); } 

In Chapter 5, “Arrays,” the nongeneric interface IComparable that requires an object with the CompareTo() method is implemented with the Person class to sort persons by lastname:

     public class Person : IComparable    {        public int CompareTo(object obj)        {           Person other = obj as Person;           return this.lastname.CompareTo(other.lastname);        } //.... 

When implementing the generic version, it is no longer necessary to cast the object to a Person:

     public class Person : IComparable<Person>    {       public int CompareTo(Person other)        {          return this.lastname.CompareTo(other.lastname);       } //... 




Professional C# 2005 with .NET 3.0
Professional C# 2005 with .NET 3.0
ISBN: 470124725
EAN: N/A
Year: 2007
Pages: 427

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net