无法过载!=操作员因错误3而需要匹配的操作员?

编程入门 行业动态 更新时间:2024-10-23 18:22:43
本文介绍了无法过载!=操作员因错误3而需要匹配的操作员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

无法过载!=,错误3操作员'ConsoleApplication13.pl.operator!=(ConsoleApplication13.pl,ConsoleApplication13.pl)'需要匹配的运算符'=='也要定义C:\ Users \ htg\documents\visual studio 2013 \Projects\ConsoleApplication13 \ConsoleApplication13 \Program.cs 37 28 ConsoleApplication13。 t $ / b

Unable To Overload != , Error 3 The operator 'ConsoleApplication13.pl.operator !=(ConsoleApplication13.pl, ConsoleApplication13.pl)' requires a matching operator '==' to also be defined C:\Users\htg\documents\visual studio 2013\Projects\ConsoleApplication13\ConsoleApplication13\Program.cs 37 28 ConsoleApplication13 . t

class Program { static void Main(string[] args) { pl a ,b,c; a= new pl(); b=new pl(); a.mark=99; b.mark=10; c = a+b; if (c != b) Console.WriteLine("is not equal"); else Console.WriteLine("both are equal"); Console.WriteLine(c.mark); Console.ReadLine(); } } class pl { public int mark; public static pl operator+ ( pl a , pl b) // 1. here It Work's Perfectly At + overloading { pl mm = new pl(); mm.mark = a.mark + b.mark; return mm; } public static bool operator!= (pl m , pl n) // 2. unable to overload { if (m.mark != n.mark) return true; else return false; } }

推荐答案

是的,需要为==和!=实现重载if你实现了其中一个。 有一个非常标准的方法,你也应该实现.Equals方法的重叠: Yes, it is required to implement overloads for both == and != if you implement one of them. There's a very standard way of doing this, and you should also implement an over-ride for the .Equals method: public class SomeClass { public string ClassName { set; get; } public SomeClass(string name) { ClassName = name; } protected bool Equals(SomeClass other) { return string.Equals(ClassName, other.ClassName); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((SomeClass)obj); } public override int GetHashCode() { return (ClassName != null ? ClassName.GetHashCode() : 0); } public static bool operator ==(SomeClass c1, SomeClass c2) { return c1.ClassName == c2.ClassName; } public static bool operator !=(SomeClass c1, SomeClass c2) { return !(c1 == c2); } }

这不是一个问题,但不难看出你缺少什么。您需要实现==和!=(或者都不是)。如果您考虑一下,您可能会理解这是一个非常合乎逻辑的规则。
-SA
This is not a question, but it's not hard to see what you are missing. It is required that you implemented both == and != (or none of them). If you think about it, you may understand that this is a pretty logical rule.
—SA

更多推荐

无法过载!=操作员因错误3而需要匹配的操作员?

本文发布于:2023-11-23 20:58:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622848.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:操作员   错误

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!