C# - Polymorphism confusing overloading and method hiding -
i have class named item
acts abstract class, not defined one. class has maxperstack
property:
public class item { public short maxperstack { { return this.data.maxperstack; } } }
i have class named equip
derives item
class , has property named maxperstack
declared new
:
public class equip : item { public new short maxperstack { { return 1; } } }
i have following method called add
, uses maxperstack
property of item
:
public void add(item item) { console.writeline("stack: {0}.", item.maxperstack); }
when do:
add(new equip());
it goes maxperstack
property of item
rather equip
one.
why's happening?
because didn't mark item.maxperstack
virtual
, , didn't mark equip.maxperstack
override
. need both of things behavior you're expecting.
by implicitly marking base type's method sealed
, explicitly marking derived type new
you're preventing virtual dispatch, exact mechanism used ensure method called on base type execute implementation associated actual runtime type of object, rather statically binding method implementation in compile time type of object.
Comments
Post a Comment