gpt4 book ai didi

c# - 为什么TimeSpan和Guid Structs可以比作null?

转载 作者:IT王子 更新时间:2023-10-29 04:47:41 27 4
gpt4 key购买 nike

我注意到某些 .NET 结构可以与 null 进行比较。例如:

  TimeSpan y = new TimeSpan();
if (y == null)
return;

将编译得很好(与 Guid 结构相同)。
现在我知道结构是值类型并且上面的代码不应该编译,除非有一个重载的运算符 == 接受一个对象。但是,据我所知,没有。
我看过 Reflector 的类(class),也看过 MSDN 上的文档。
他们两个确实实现了以下接口(interface):

IComparable, IComparable<T>, IEquatable<T>

但是,尝试实现相同的接口(interface)似乎没有帮助:

struct XX : IComparable, IComparable<XX>, IEquatable<XX> {
public int CompareTo(Object obj) {
return 0;
}
public int CompareTo (XX other){
return 0;
}
public bool Equals (XX other){
return false;
}
public override bool Equals(object value){
return false;
}
public static int Compare(XX t1, XX t2){
return 0;
}
}

我正在使用:.NET 2.0 Visual Studio 2005。

有人知道这是什么原因吗?我只是想获得更好的理解。这不是问题,因为我知道无论如何我都不应该将结构与 null 进行比较。

最佳答案

它是 == 运算符。

TimeSpan 类重载了相等运算符:

public static bool operator ==(DateTime d1, DateTime d2)
{
return (t1._ticks == t2._ticks);
}

这本身并不能与 null 进行比较,但是...

随着可空类型的到来,每个结构都可以隐式转换为其可空类型,所以当您看到类似的东西时

TimeSpan y = new TimeSpan();
if (y == null)
return;

没有看到这正在发生:

TimeSpan y = new TimeSpan();
if ((Nullable<TimeSpan>)y == (Nullable<TimeSpan>)null)
return;

Null 获得隐式转换(隐式赋值?),但并非所有 System.Object 对象都这样做:

TimeSpan y = new TimeSpan();
object o = null;
if (y == o) //compiler error
return;

好的,但是相等运算符不接受可为 null 的参数,对吗?

嗯,msdn在这里有帮助,说明:

The predefined unary and binary operators and any user-defined operators that exist for value types may also be used by nullable types. These operators produce a null value if [any of] the operands are null; otherwise, the operator uses the contained value to calculate the result.

因此,您可以有效地免费为每个运算符实现可为 null 的实现,并具有固定的定义行为。上面提到的“包含值”是非可空运算符将返回的实际值。

关于c# - 为什么TimeSpan和Guid Structs可以比作null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1225949/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com