Pau*_*aul 2 c# generics type-constraints
我想做类似下面的事情,但因为T本质上只是一个System.Object,所以这不起作用.我知道T可以受到接口的限制,但这不是一个选择.
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..
}
}
}
Run Code Online (Sandbox Code Playgroud)
我经常发现C#generics缺乏.
谢谢!
保罗
泛型的全部意义在于,您可以为任何有效类型执行相同的操作.
如果您真的在为类型做特定的事情,那么该方法不再是通用的,应该为每种特定类型重载.
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 }
}
Run Code Online (Sandbox Code Playgroud)