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# 隐式转换和 == 运算符
				
        
 
            
        基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
 - 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
 - JSON.NET 中基于属性的类型解析 2022-01-01
 - 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
 - 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
 - 全局 ASAX - 获取服务器名称 2022-01-01
 - 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
 - 首先创建代码,多对多,关联表中的附加字段 2022-01-01
 - 错误“此流不支持搜索操作"在 C# 中 2022-01-01
 - 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				