开发者

Is there a technique to differentiate class behavior on generic types?

I'd like to do something like the following, but because T is essentially just a System.Object this won't work. I know T can be constrained by an interface, but that isn't an option.

public class Vborr<T> where T : struct
  {

    public Vborr()
    {
    public T Next()
    {
      if ( typeof( T ) == typeof( Double ) )
      {
      开发者_如何学运维   // do something for doubles
      }
      if ( typeof( T ) == typeof( Float ) )
      {
         // do something different for floats..
      }
    }
  }

I frequently find C# generics lacking.

Thanks!

Paul


The whole point of generics is that you can do the same thing for any valid type.

If you're truly doing something specific for the types, then the method isn't generic anymore and should be overloaded for each specific type.

public class Vborr<T> where T : struct
{
    public virtual T Next() { // Generic Implementation }
}

public class VborrInt : Vborr<int>
{
    public override int Next() { // Specific to int }
}

public class VborrDouble : Vborr<double>
{
    public override double Next() { // Specific to double }
}


The approach I would take here would be that of a factory pattern and creating specialized instances of Vborr based off of the type. For example

public class Vborr<T> where T : struct {
  protected Vborr() { }
  abstract T Next();
}

public static class VborrFactory { 
  private sealed class VborrFloat : Vborr<float> {
    public VborrFloat() {}
    public override float Next() {
      ...
    }
  }
  private sealed class VborrDouble : Vborr<double> {
    public VborrDobule() {}
    public override double Next() {
      ...
    }
  }
  private sealed class VborrDefault<U> : Vborr<U> {
    public VborrDefault() {}
    public override U Next() {
      ...
    }
  }
  public static Vborr<T> Create<T>() {
    if (typeof(T) == typeof(double) ) { 
      return new VborrDouble();
    } else if ( typeof(T) == typeof(float) ) {
      return new VborrFloat();
    } else {
      return new VborrDefault<T>();
    }
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜