测试是否等于默认值

编程入门 行业动态 更新时间:2024-10-27 20:34:11
本文介绍了测试是否等于默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

以下内容无法编译:

public void MyMethod<T>(T value) { if (value == default(T)) { // do stuff } }

错误:运算符'=='无法应用于类型'T'和'T'的操作数

Error: Operator '==' cannot be applied to operands of type 'T' and 'T'

我不能使用 value == null ,因为 T 可能是一个结构。 我不能使用 value.Equals(default(T))因为 value 可能为 null 。 什么是测试与否相等的正确方法?

I can't use value == null because T may be a struct. I can't use value.Equals(default(T)) because value may be null. What is the proper way to test for equality to the default value?

推荐答案

以避免为 struct 装箱/ Nullable< T> ,我会使用:

To avoid boxing for struct / Nullable<T>, I would use:

if (EqualityComparer<T>.Default.Equals(value,default(T))) { // do stuff }

这支持任何实现 IEquatable< T> ,使用 object.Equals 作为备份,并处理 null 等(并取消了自动为Nullable )。

This supports any T that implement IEquatable<T>, using object.Equals as a backup, and handles null etc (and lifted operators for Nullable<T>) automatically.

还有 Comparer< T>。默认处理比较测试。这处理实现 IComparable< T> 的 T ,回退到 IComparable -再次处理 null 并取消了运算符。

There is also Comparer<T>.Default which handles comparison tests. This handles T that implement IComparable<T>, falling back to IComparable - again handling null and lifted operators.

更多推荐

测试是否等于默认值

本文发布于:2023-10-26 22:13:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1531495.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:默认值   测试

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!