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;
是否可以在不同类型实例上使用 == 运算符,其中一个实例可以隐式转换为另一种实例? 我错过了什么?
编辑:
如果调用 == 时类型必须相同,那为什么
int a=1;
double b=1;
bool c=a==b;
有效呢?
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?
Edit:
If types must be the same calling ==, then why
int a=1;
double b=1;
bool c=a==b;
works?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
隐式
运算符仅适用于赋值。您想要重载相等 (
==
) 运算符,如下所示:这应该允许您比较
a
和b
类型的两个对象正如你的帖子中所建议的。注意:
我建议简单地覆盖
GetHashCode
和Equals
方法,正如编译器警告的那样,但是当您似乎想要抑制它们时,您可以按如下方式进行操作。将
a
的类声明更改为:The
implicit
operator only works for assignment.You want to overload the equality (
==
) operator, as such:This should then allow you to compare two objects of type
a
andb
as suggested in your post.Note:
I recommmend simply overriding the
GetHashCode
andEquals
method, as the compiler warns, but as you seem to want to supress them, you can do that as follows.Change your class declaration of
a
to:是的。
这是规范的相关部分。 您错过了突出显示的单词。
根据定义,用户定义的转换不是标准转换。 这些是参考类型。 因此,预定义的引用类型相等运算符不是候选者。
您认为类型必须相同的假设是不正确的。 有一个从 int 到 double 的标准隐式转换,并且有一个接受两个双精度数的相等运算符,因此这是有效的。
我想你也错过了这一点:
Yes.
Here's the relevant portion of the specification. You missed the highlighted word.
A user-defined conversion is by definition not a standard conversion. These are reference types. Therefore, the predefined reference type equality operator is not a candidate.
Your supposition that the types must be the same is incorrect. There is a standard implicit conversion from int to double and there is an equality operator that takes two doubles, so this works.
I think you also missed this bit:
我想您需要实际覆盖您感兴趣的类型的 == 运算符。即使类型是隐式可转换的,编译/运行时是否仍然会抱怨,您必须进行试验。
或者,只需使用 ole6ka 建议的 Equals 实现,并确保该实现执行您需要的类型转换。
I would imagine that you need to actually override the == operator for the types you are interested in. Whether the compile/runtime will still complain even if the types are implicity convertable is something you'll have to experiment with.
Alternatively just use Equals implementations like ole6ka suggests and ensure that the implementation does the type casting you need.
http://msdn.microsoft.com/en-us/library/8edha89s。 ASPX
http://msdn.microsoft.com/en-us/library/8edha89s.aspx
用这个
Use this