在C++中,有人可以编写以下代码片段:
当然,这里只有简单的测试样本。实际代码更加复杂。事实上,我只想知道在 C# 中是否有可能测试两个泛型类型参数的相等性。
#include <type_traits>
template <typename Type1, typename Type2>
bool TestArgumentTypesOnEquality(Type1 argument1, Type2 argument2)
{
return std::is_same<Type1, Type2>::value;
}
std::is_same
类模板检查Type1
和Type2
(它们是TestArgumentTypesOnEquality
函数模板参数的类型)是否相等。
是否有C#泛型的类似功能来实现这个C++标准库的功能呢?
public static bool TestArgumentTypesOnEquality<Type1, Type2>(Type1 argument1, Type2 argument2)
{
return /* ??? */;
}
当然,这里只有简单的测试样本。实际代码更加复杂。事实上,我只想知道在 C# 中是否有可能测试两个泛型类型参数的相等性。
argument1.GetType()== argument2.GetType()
,区别在于调用TestArgumentTypesOnEquality(1,(object)2)
将为GetType
返回true,但对于typeof
则为false。 - juharrif (typeof(Type1) == typeof(Type2)) ...
有什么问题吗? - usr