C#.NET中的泛型类型参数约束

ser*_*0ne 9 .net c# generics constraints

考虑以下Generic类:

public class Custom<T> where T : string
{
}
Run Code Online (Sandbox Code Playgroud)

这会产生以下错误:

'string'不是有效的约束.用作约束的类型必须是接口,非密封类或类型参数.

是否有另一种方法来约束我的泛型类可以使用哪些类型?

另外,我可以约束多种类型吗?

例如

T只能是string,int或byte

Mar*_*ell 16

public class Custom<T> where T : string
Run Code Online (Sandbox Code Playgroud)

是不允许的,因为只有 T符合即:string(stringsealed) -使得它相当无意义作为一种通用的.

另外,我可以约束多种类型吗?

不 - 除非你在运行时通过反射而不是在约束中执行此操作(静态构造函数是一种方法 - 如果使用不正确则抛出异常)

T can only be string, int or byte

可能会使用类似的东西IEquatable<T>,但这并没有像你想的那样限制它,所以最终:不.

可以做的是通过重载工厂访问它:

public abstract class Custom
{
    public static Custom Create(int value)
    { return new CustomImpl<int>(value); }
    public static Custom Create(byte value)
    { return new CustomImpl<byte>(value); }
    public static Custom Create(string value)
    { return new CustomImpl<string>(value); }
    private class CustomImpl<T> : Custom
    {
        public CustomImpl(T val) { /*...*/ }
    }
}
Run Code Online (Sandbox Code Playgroud)