below is a code example from a book to show when a value type will be boxed:
internal struct Point
{
private readonly Int32 m_x, m_y;
public Point(Int32 x, Int32 y) {
m_x = x;
m_y = y;
}
//Override ToString method inherited from System.ValueType
public override string ToString() {
return String.Format("({0}, {1})", m_x.ToString(), m_y.ToString());
}
}
class Program
{
static void Main(string[] args) {
Point p1 = new Point(10, 10);
p1.ToString();
}
}
and the author says:
In the call to ToString, p1 doesn’t have to be boxed. At first, you’d think that p1 would have to be boxed because ToString
is a virtual method that is inherited from the base type, System.ValueType. Normally, to call a virtual method, the CLR needs to determine the object’s type in order to locate the type’s method table. Because p1 is an unboxed value type, there’s no type object pointer. However, the just-in-time (JIT) compiler sees that Point overrides the ToString method, and it emits code that calls ToString directly (nonvirtually) without having to do any boxing. The compiler knows that polymorphism can’t come into play here because Point is a value type, and no type can derive from it to provide another implementation of this virtual method.
I kind of get what it means, because Point
overrides ToString
from System.ValueType
, CLR doesn't need to check the type object to locate the type’s method table, the compiler can emits IL code that calls ToString directly. Fair enough.
But let's say p1
also calls GetHashCode
from System.ValueType
as:
class Program
{
static void Main(string[] args) {
Point p1 = new Point(10, 10);
p1.ToString();
p1.GetHashCode();
}
}
since Point
struct doesn't override GetHashCode()
from System.ValueType
, then compiler cannot emit IL codes directly this time and CLR needs to location the type’s method table to look up GetHashCode
method, but as the author says p1 is an unboxed value type, there’s no type object pointer, so how can the CLR look up the GetHashCode
method in Point
struct's type object in heap?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…