`

c# - design of generic version of interface with its non generic verion

    博客分类:
  • C#
c# 
阅读更多

sometimes you may want to design some interfaces so that it can handle both generic classes and the non-generic classes.  The reason for oding this is 1. for backward compatability 2. you may deal with data with determined parameter type T or data whose type is object. 

 

A typical example of this is the IEnumerable interface, where 

 

public interface IEnumerable
{
    IEnumerator GetEnumerator();
}


 
public interface IEnumerable<out T> : IEnumerable
{
    IEnumerator<T> GetEnumerator();
}

 

 

Below I provided the skeleton to implements such classes that inherits from the generic/non-generic interfaces. 

  interface IInterface
  {
    object Object { get; } 
  }

  interface IInterface<T> : IInterface
  {
    T Object { get; } 
  }

  class NonGeneric : IInterface
  {
    protected object obj;

    public object Object { 
      get { return obj; } 
    } 
  }

  class Generic<T> : NonGeneric, IInterface<T>, IInterface
  {
    object IInterface.Object { get { return base.obj; } }

    public T Object { get { return (T)base.obj; } }

  }

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics