我想做类似下面的事情,但是因为 T 本质上只是一个 System.Object 这行不通。我知道 T 可以通过接口(interface)进行约束,但这不是一种选择。
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..
}
}
}
我经常发现缺少 C# 泛型。
谢谢!
保罗
最佳答案
泛型的全部意义在于您可以对任何有效类型做同样的事情。
如果您真的是在为这些类型做一些特定的事情,那么该方法就不再是通用的了,应该为每个特定类型重载。
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 }
}
关于c# - 有没有一种技术可以区分泛型类型的类行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3943701/