c# - 可重载运算符 == 和 !=

标签 c# c#-4.0 c#-3.0 operator-overloading

我有 2 个类:

public class Item {
   //MyFields
}

public class ItemCapsule {
    public Item MyItem { get; set; };
}

在代码的某处,我写

ItemCapsule itemCapsule;
if (itemCapsule  != null && itemCapsule.MyItem != null) {
    //action
}

我可能想这样做:

ItemCapsule itemCapsule;
if (itemCapsule  != null) {
    //action
}

所以我在 ItemCapsule 中创建了 2 个重载运算符的方法

public static bool operator ==(ItemCapsule capsule, ???? what to write ????)
{
    return ???? what to write ????;
}

public static bool operator !=(ItemCapsule capsule, ???? what to write ????)
{
    return ???? what to write ????;
}

但是,问题是我不知道如何写上面的两个方法。

我要执行以下操作

ItemCapsule != null

实际上应该执行以下操作

ItemCapsule != null && ItemCapsule.MyItem != null

我该怎么做?

最佳答案

通常你也会为 equals 做一个重载。

像这样

        public static bool operator ==(ItemCapsule  x, ItemCapsule  y)
        {
            bool xnull, ynull;
            xnull = Object.ReferenceEquals(x, null);
            ynull = Object.ReferenceEquals(y, null);
            if (xnull && ynull) return true;
            if (xnull || ynull) return false;
            return x.Equals(y);
        }

        public static bool operator !=(ItemCapsule  x, ItemCapsule  y)
        {
            bool xnull, ynull;
            xnull = Object.ReferenceEquals(x, null);
            ynull = Object.ReferenceEquals(y, null);
            if (xnull && ynull) return false;
            if (xnull || ynull) return true;
            return !x.Equals(y);
        }

        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            return ((ItemCapsule )obj).Id == Id;
        }

关于c# - 可重载运算符 == 和 !=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14951596/

相关文章:

c# - InvalidOperationException:调度程序处理已暂停,但消息仍在处理中

c# - 3秒后使用c#刷新页面

c# - 在 .NET 4.0 (C#) 中动态实现接口(interface)

c# - 具有集合类型的 CodeContracts

web-services - 如何添加 <soap :Header> tag? WSDL 未与这些信息一起出现

c# - 对象作为字典中的键

c# - C#-从类内部调用方法

c# - 使用流通过 Json.NET 创建 BSON 字节数组(文件格式)

c# - 刷新 ListView 以显示所选索引?

c# - 彻底理解linq