C# not running derived class function -
i have problem game i'm making. have lot of fields, basic type , other types. logically made derivatives of basic field add functionality needed.
however, seems when call function present in base class, function ran base class , not derivative.
here cut-down code can see mean.
public class field { public field(field exitn, field exite, field exits, field exitw, bool barricadeallowed, int returnto, int xpos, int ypos) { //actual logic in constructor, unrelated below function } public void function() { if (this startfield) { debug.writeline("startfield running base function!"); } //actual logic here. } }
.
class startfield : field { public startfield(field exitn, field exite, field exits, field exitw, string color, int xpos, int ypos) : base(exitn, exite, exits, exitw, false, 0, xpos, ypos) { //again, constructor emptied due unrelatedness. } public new void function() { debug.writeline("startfield function"); //different logic base function }
calling funtion on startfield object causes "startfield running base function!" appear in debug bar, not "startfield function" tells me base function called though object knows of type startfield.
if makes difference, fields saved through links other fields. variables ask type field, allowed in variables (because inheritance) can in way cause call go "field" code rather "startfield" code (or code of other non standard field, since seems case fields)
there 2 workarounds can think of first workaround can think of checking type , casting field it's actual type before running function. we're not allowed use (class field) in assignment. plus require more code needed simple function call.
the second workaround uses (class field) functionality, namely programming field type functionality base class. not uses (class field) feels plain wrong (childs should have own functionality, doesn't make sense if base has all. might go single class , have type variable instead of inheriting member)
what if function
made virtual?
public virtual void function() { if (this startfield) { debug.writeline("startfield running base function!"); } //actual logic here. }
and overridden in startfield
, this:
public override void function() { debug.writeline("startfield function"); //different logic base function }
Comments
Post a Comment