泛型参数:确保类型不同



我有一个带有两个泛型参数的类。我想将第二个泛型参数限制为与第一个不同的类型。有没有办法在编译时做出这样的限制?在运行时检查类型不是很有用。

public class Test<A, B>
    where B : not_typeof(A)
{
    // ...
}

唯一的方法是在运行时。

我根据我在评论中发布的答案改编了这个答案。

public class Test<A, B> {
    static Test() {
        if (typeof(B) == typeof(A)) {
            throw new NotSupportedException("Argument B is not supported.");
        }
    }
}

最新更新