C# 泛型类接受基元类型和字符串

C# 泛型类接受基元类型和字符串,c#,generics,collections,C#,Generics,Collections,如何创建一个泛型类型,该类型只接受整数、Long和String类型。 我知道我们可以将一个类型限制为单个类,或者通过使用下面的代码实现一个接口 public class MyGenericClass<T> where T:Integer{ } 公共类MyGenericClass其中T:Integer{} 或者处理int,long,而不是string public class MyGenericClass<T> where T:struct 公共类MyGeneric

如何创建一个泛型类型,该类型只接受整数、Long和String类型。

我知道我们可以将一个类型限制为单个类,或者通过使用下面的代码实现一个接口

public class MyGenericClass<T> where T:Integer{ }
公共类MyGenericClass其中T:Integer{}
或者处理int,long,而不是string

public class MyGenericClass<T> where T:struct 
公共类MyGenericClass其中T:struct

是否可以创建一个只接受整型、长型和字符串类型的泛型?

在类声明中可能没有约束,但在静态构造函数中执行一些类型检查:

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>
公共类MyGenericClass
{
静态MyGenericClass()//为每种类型的T调用一次
{
if(typeof(T)!=typeof(string)&&
typeof(T)!=typeof(int)&&
类型(T)!=类型(长)
抛出新异常(“指定的类型无效”);
}//行政长官
}//eo类MyGenericClass
编辑:


正如马修·沃森(Matthew Watson)在上文中指出的,真正的答案是“你不能也不应该”。如果你的面试官认为这是不正确的,那么你可能无论如何都不想在那里工作;)

我建议您使用构造函数来显示哪些值是可接受的,然后将该值存储在对象中。例如:

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();
    }
}

你确定泛型是你想要的吗?泛型通常被广泛使用。“你到底想解决什么问题?”采访者问道。我问他需要什么,他回答说这是要求(我的回答是“你不能,如果你可以的话,它也不是一般的。写三个不同的类吧。”是否可以进行编译时检查?这限制了runtime@Billa,否,但您可以添加一些附加接口以减少可能出现的情况,例如
i可比较、i可转换
@chrisnclair,“从不”有点太强了-有了完全信任权限,你可以做各种讨厌的事情,@Lucero哈哈,很公平。你仍然可以像上面那样应用运行时检查,但这可以在编译时提供一些保证,比如说,除了愚蠢之外一切都正常。@JonnyPiazzi这是一个采访问题……谁知道为什么?