C# 隐式转换和 == 运算符 [英] C# implicit conversions and == operator

查看:22
本文介绍了C# 隐式转换和 == 运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一些上下文代码:

class a
{

}

class b
{
    public a a{get;set;}
    public static implicit operator a(b b)
    {
        return b.a;
    }
}

  a a=null;
  b b=null;
  a = b;

  //compiler: cannot apply operator '==' to operands of type tralala...
  bool c = a == b; 

是否可以在不同类型的实例上使用 == 运算符,其中一个可以隐式转换为另一个?我错过了什么?

Is it possible to use == operator on different type instances, where one can implicitly convert to another? What did i miss?


如果类型必须是相同的调用==,那么为什么


If types must be the same calling ==, then why

int a=1;
double b=1;
bool c=a==b; 

有效吗?

推荐答案

implicit 运算符仅适用于赋值.

The implicit operator only works for assignment.

您想重载相等 (==) 运算符,如下所示:

You want to overload the equality (==) operator, as such:

class a
{
    public static bool operator ==(a x, b y)
    {
        return x == y.a;
    }

    public static bool operator !=(a x, b y)
    {
        return !(x == y);
    }
}

class b
{
    public a a{get;set;}
    public static implicit operator a(b b)
    {
        return b.a;
    }
}

这应该允许您按照帖子中的建议比较 ab 类型的两个对象.

This should then allow you to compare two objects of type a and b as suggested in your post.

var x = new a();
var y = new b();
bool c = (x == y); // compiles

注意:

我建议简单地覆盖 GetHashCodeEquals 方法,正如编译器警告的那样,但是当您似乎想要抑制它们时,您可以按如下方式进行.

I recommmend simply overriding the GetHashCode and Equals method, as the compiler warns, but as you seem to want to supress them, you can do that as follows.

a 的类声明更改为:

Change your class declaration of a to:

#pragma warning disable 0660, 0661
class a
#pragma warning restore 0660, 0661
{
    // ...
}

这篇关于C# 隐式转换和 == 运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆