C# implicit conversions and == operator(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;
}
}
这应该允许您按照帖子中的建议比较 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 的类声明更改为:
Change your class declaration of a to:
#pragma warning disable 0660, 0661
class a
#pragma warning restore 0660, 0661
{
// ...
}
这篇关于C# 隐式转换和 == 运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 隐式转换和 == 运算符
基础教程推荐
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 如果条件可以为空 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 将数据集转换为列表 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
