C#隐式转换和==运算符 [英] C# implicit conversions and == operator
问题描述
一些用于上下文的代码:
Some code for context:
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;
}
}
然后,您应该可以按照帖子中的建议比较两个类型为a
和b
的对象.
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
注意:
我建议您像编译器警告的那样简单地覆盖GetHashCode
和Equals
方法,但是由于您似乎想抑制它们,您可以按照以下步骤进行操作.
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
的类声明更改为:
#pragma warning disable 0660, 0661
class a
#pragma warning restore 0660, 0661
{
// ...
}
这篇关于C#隐式转换和==运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!