如何覆盖一个基类的==运算符,所以覆盖得到调用 [英] How can i override a base class's == operator, so the override gets called
本文介绍了如何覆盖一个基类的==运算符,所以覆盖得到调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通过类似下面的
public class Task
{
string Name;
public static bool operator ==(Task t1, Task t2)
{ return t1.Name = t2.Name && t1.GetType() == t2.GetType(); }
}
public class TaskA : Task
{
int aThing;
public static bool operator ==(TaskA t1, TaskA t2)
{
return (Task)t1 == (Task)t2 && t1.GetType() == t2.GetType()
&& t1.aThing == t2.aThing; }
}
public class TaskB : Task //more of the same
class Stuffin
{
List<Task> Tasks;
void CheckIt()
{
bool theSame = Tasks[0] == Tasks[1];
}
我想,以确保衍生运算符(TASKA == )被调用。
I'm trying to make sure that the derived operator (TaskA.==) is called.
尝试该技术的这里。
我想我能够得到它才能正常工作,如果运营商是不是静态的,因为我可以再重写基类的运营商。这可能吗?
I think i'd be able to get it to work correctly if the operator was not static, because i could then override the base class's operator. Is that possible?
一旦我得到如何将我比较基本属性(我想投给任务类型[(任务)T1 ==(任务)T2 ]不工作)?
Once i get that how would i compare the base properties (i would think the cast to task type [(Task)t1 == (Task)t2] would not work)?
推荐答案
我的混合解决方案,似乎工作。
My hybrid solution that seems to work.
public class Task
{
string Name;
public static bool operator ==(Task t1, Task t2)
{
if ((object)t1 == null || (object)t2 == null)
{
return (object)t1 == null && (object)t2 == null;
}
return t1.Name == t2.Name && t1.GetType() == t2.GetType(); }
public virtual bool Equals(Task t2)
{
return this == t2;
}
}
public class TaskA : Task
{
int aThing;
public static bool operator ==(TaskA t1, TaskA t2)
{
if ((object)t1 == null || (object)t2 == null)
{
return (object)t1 == null && (object)t2 == null;
}
return (Task)t1 == (Task)t2 && t1.aThing == t2.aThing;
}
public override bool Equals(Task t2)
{
return this == t2 as TaskA;
}
}
这篇关于如何覆盖一个基类的==运算符,所以覆盖得到调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文