我已阅读以下有关 C# 值类型比较的声明 在 C# in Depth, Second Edition 中多次。
第 77 页,
When a type parameter is unconstrained (no constraints are applied to it), you can use == and != operators, but only to compare a value of that type with null. You can’t compare two values of type T with each other.
...
When a type parameter is constrained to be a value type, == and != can’t be used with it at all.
如果我理解正确(我不这么认为),它基本上告诉我你不能 使用 == 或 != 比较两个值类型。为什么为什么为什么?
这种情况如果能给出一个简单的例子就更好了。谁能给我 对以上段落试图传达的内容有一点了解吗?
最佳答案
当约束到一个值类型(第二段)时,它只是意味着这个
static bool TryToCompare<T>(T first, T second) where T : struct
{
return first == second; // not legal
return first.Equals(second); // legal
}
没有泛型的值类型约束,也是这样说的(第一段)
static bool TryToCompare<T>(T first, T second)
{
return first == second; // not legal
return first == null; // legal
return first.Equals(second); // legal
}
如果将 T
限制为引用类型,则可以使用 ==
static bool TryToCompare<T>(T first, T second) where T : class
{
return first == second; // legal
return first == null; // legal
return first.Equals(second); // legal
}
关于c# - C# 值类型的直接比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6222487/