Get hashcode of parent class from inherited class
Consider these classes:
public class BaseClass {
public int SomeInt { get; set; }
public bool SomeBool { get; set; }
public BaseClass(int i, bool b) {
SomeInt = i;
SomeBool = b;
}
}
public class InheritedClass : BaseClass {
public List<Int32> SomeInts { get; set; }
public InheritedClass(int i, bool b, List<Int32> ints): base(i, b) {
SomeInts = ints;
}
public InheritedClass(BaseClass b, List<Int32> ints) : base(b.SomeInt, b.SomeBool) {
SomeInts = ints;
}
}
And I've got an instance of InheritedClass
, I want to get the HashCode value of it if it were a BaseClass
. I've tried casting it:
BaseClass x = new BaseClass(10, true);
Console.WriteLine("HashCode x: {0}", x.GetHashCode());
InheritedClass iX = new InheritedClass(x, new List<int> { 1, 2, 3 });
Console.WriteLine("HashCode iX: {0}",开发者_如何学JAVA iX.GetHashCode());
BaseClass bX = (BaseClass)iX;
//I've also tried:
//BaseClass bX = ix as BaseClass;
Console.WriteLine("Base HashCode bX: {0}", bX.GetHashCode());
But the final WriteLine
is returning the hashcode as if it was an InhertiedClass
. I can't overide the GetHashCode
of the InheritedClass
, and save constructing a new BaseClass
from the properties of the object, is there anyway to get the HashCode I need?
Individual objects have a HashCode.
And as long as you don't override GetHashCode()
, the value is totally independent of the class (Base or Derived) of the object.
The hashcode for an instance of anything will be the same no matter how you cast it. Irrespective of how you are 'viewing' it, you are still looking at the same object in memory. The only way I can think of to do this is to clone it as the base type (so you have an actual instance of the base class) and then hash it.
Add this method to InheritedClass:
public class InheritedClass : BaseClass {
public int GetBaseHashCode()
{
return base.GetHashCode();
}
}
Then call iX.GetBaseHashCode();
Note: I'm assuming that you are overriding GetHashCode()
for InheritedClass
. Because otherwise these will return exactly the same value.
Since neither of your classes override GetHashCode
then they'll use the default implementation provided by System.Object
.
The hashcode is generated for the object, so the hashcode generated for bX
is the same regardless of whether it's treated as the parent class or child class, since the same implementation of GetHashCode
is used.
If each class had its own GetHashCode
override then those overrides would be used as you expect when calling parent.GetHashCode
or child.GetHashCode
etc.
No, there isn't unless you provide such a method in your inherited class. Just because you cast something doesn't mean it's identity changes. Also, what if you have two instances, that have the same hashcode as the baseclass, but different as the inherited, as a field/property changed?
精彩评论