C# - 有没有办法限制两个类型参数必须不同?
C# - Is there a way to constrain two type parameters to be necessarily different?
我正在构建一个 MyClass<T1, T2> : IEnumerable<Tuple<T1, T2>>
class,但要使其在我的应用程序上下文中具有任何意义,我需要确保 T1 != T2
.
是否有适当的方法来约束 T1
和 T2
以使它们不是同一类型?
如果您知道它们应该是什么类型,您可以使用 where
类型约束:
class MyClass<T1, T2> : IEnumerable<Tuple<T1, T2>>
where T1 : MyClass1
where T2 : MyClass2
但是没有办法允许它们是任意的class,而是强制它们不相等。您可能必须在构造函数中抛出异常:
if (typeof(T1) == typeof(T2)) {
throw new Exception("Types must not be the same.");
}
我正在构建一个 MyClass<T1, T2> : IEnumerable<Tuple<T1, T2>>
class,但要使其在我的应用程序上下文中具有任何意义,我需要确保 T1 != T2
.
是否有适当的方法来约束 T1
和 T2
以使它们不是同一类型?
如果您知道它们应该是什么类型,您可以使用 where
类型约束:
class MyClass<T1, T2> : IEnumerable<Tuple<T1, T2>>
where T1 : MyClass1
where T2 : MyClass2
但是没有办法允许它们是任意的class,而是强制它们不相等。您可能必须在构造函数中抛出异常:
if (typeof(T1) == typeof(T2)) {
throw new Exception("Types must not be the same.");
}