如何创建一个只接受Integer、Long和String类型的通用类型?
我知道我们可以通过以下代码为单个类或通过实现接口来限制类型:
public class MyGenericClass<T> where T:Integer{ }
或者处理整型、长整型,但不包括字符串。
public class MyGenericClass<T> where T:struct
有没有可能创建一个只接受 Integer、Long 和 String 类型的通用程序?
如何创建一个只接受Integer、Long和String类型的通用类型?
我知道我们可以通过以下代码为单个类或通过实现接口来限制类型:
public class MyGenericClass<T> where T:Integer{ }
或者处理整型、长整型,但不包括字符串。
public class MyGenericClass<T> where T:struct
有没有可能创建一个只接受 Integer、Long 和 String 类型的通用程序?
在类声明中,你可能没有限制条件,但可以在静态构造函数中进行一些类型检查:
public class MyGenericClass<T>
{
static MyGenericClass() // called once for each type of T
{
if(typeof(T) != typeof(string) &&
typeof(T) != typeof(int) &&
typeof(T) != typeof(long))
throw new Exception("Invalid Type Specified");
} // eo ctor
} // eo class MyGenericClass<T>
编辑:
正如Matthew Watson在上面指出的那样,真正的答案是“你不能也不应该这样做”。如果你的面试官认为那是不正确的,那么你可能也不想在那里工作 ;)
IComparable, IConvertible
。 - Lucero我建议您使用构造函数来展示哪些值是可接受的,然后将该值存储在对象中。如下所示:
class MyClass
{
Object value;
public MyClass(int value)
{
this.value = value;
}
public MyClass(long value)
{
this.value = value;
}
public MyClass(string value)
{
this.value = value;
}
public override string ToString()
{
return value.ToString();
}
}