只能采用某些类型的泛型类

use*_*312 5 c# generics c#-2.0

假设,我想创建一个只能采用intdouble作为类型的泛型类。

public class A<T> where T: int, double
{
    public T property{get;set;}
}
Run Code Online (Sandbox Code Playgroud)

例如:

A<int> i = new A<int>();
i.property = 10;

A<double> d = new A<double>();
d.property = 0.01;
Run Code Online (Sandbox Code Playgroud)

但是,这是行不通的。

我怎样才能做到这一点?

有没有其他方法可以满足我的特定要求?

ven*_*mit 5

C# 中不存在这样的约束。但是对于值类型,您可以将其struct用作通用约束。它只允许不可为空的值类型。

public class A<T> where T : struct
{
    public T property;
}
Run Code Online (Sandbox Code Playgroud)

您可以在构造函数中添加运行时类型检查:

public class A<T> where T : struct
{
    public T property;
    public A()
    {
        if(typeof(T) != typeof(int) || typeof(T) != typeof(double))
        {
            throw new InvalidConstraintException("Only int or double is supported");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)