泛型参数:确保类型不同

本文关键字:类型 确保 参数 泛型 | 更新日期: 2023-09-27 18:28:20

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

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.");
        }
    }
}