各位大侠:
我写了个值类型,如下:
public struct BattingAverage
{
public int _atBats;
public int _hits;
public BattingAverage(int atBats,int hits)
{
TestValid(atBats,hits);
_atBats=atBats;
_hits=hits;
}
private static void TestValid(int testAtBats,int testAtHits)
{
if(testAtBats<0)
{
string msg="At bats must not be negative";
throw new ArgumentOutOfRangeException(msg);
}
if(testAtHits<0)
{
string msg="Hits must not exceed at bats";
throw new ArgumentOutOfRangeException(msg);
}
}
public float Average()
{
if(_atBats==0)
return 0.0f;
else
return (float)_hits/(float)_atBats;
} public static bool operator ==(BattingAverage left,BattingAverage right)
{
if((object)left==null)
return false;
else
return left.Equals(right);
}
}想重载==符号,出错了!!!报什么,equal,gethashcode 错误?什么回事啊?
equals,gethashcode 到底是个什么回事?
我写了个值类型,如下:
public struct BattingAverage
{
public int _atBats;
public int _hits;
public BattingAverage(int atBats,int hits)
{
TestValid(atBats,hits);
_atBats=atBats;
_hits=hits;
}
private static void TestValid(int testAtBats,int testAtHits)
{
if(testAtBats<0)
{
string msg="At bats must not be negative";
throw new ArgumentOutOfRangeException(msg);
}
if(testAtHits<0)
{
string msg="Hits must not exceed at bats";
throw new ArgumentOutOfRangeException(msg);
}
}
public float Average()
{
if(_atBats==0)
return 0.0f;
else
return (float)_hits/(float)_atBats;
} public static bool operator ==(BattingAverage left,BattingAverage right)
{
if((object)left==null)
return false;
else
return left.Equals(right);
}
}想重载==符号,出错了!!!报什么,equal,gethashcode 错误?什么回事啊?
equals,gethashcode 到底是个什么回事?
GetHashCode
起什么作用呢?
重载==的目的: 确定两个实例是否相等所以若重载了==和!=而又不重写Equals方法,则会引起混淆,有可能会引起代码安全问题Object.GetHashCode 方法:用作特定类型的哈希函数,适合在哈希算法和数据结构(如哈希表)中使用。重写 GetHashCode 的派生类还必须重写 Equals,以保证被视为相等的两个对象具有相同的哈希代码;否则,Hashtable 可能不会正常工作。