无法过载!=操作员因错误3而需要匹配的操作员? [英] Unable To Overload != Operator Due To Error 3 requires a matching operator ?
本文介绍了无法过载!=操作员因错误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而需要匹配的操作员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文