inheritance - C# How could a superclass return back 3 possible types without casting from the calling class -
before begin, want state realize isn't ideal way of doing this. calling class can't changed according rules of assignment. have tried understand , find solution problem, have had no luck.
below there 1 superclass,treemangement (there can 1 superclass these subclasses). there 3 subclasses(apple, orange , banana). "find" method must in treemangement superclass. not allowed override "find" method. current code, casting error in calling class. state treemangement can't implicity casted appletree,orangetree or bananatree.
now question is, able somehow pass correct type calling class no matter type (apple,banana,orange) calling it, without casting in calling class? if so, how? if not, references know there absolutely no way of doing it.
public class treemangement { public string id {get; set;} public treemangement() { id = this.gettype().name+"|"+guid.newguid(); } public static treemangement find(string idin) { string type = idin.split('|')[0]; return functions.getobj(idin, getfilepath(type), type); //returns right type } } public class appletree:treemangement { public string name; } public class orangetree:treemangement { public string name; } public class bananatree:treemangement { public string name; } ///////calling class//// appletree savedappletree = appletree.find("somevalidid"); orangetree savedorangetree = orangetree.find("somevalidid"); bananatree savedbananatree = bananatree.find("somevalidid");
you can change superclass generic superclass this:
public class treemangement<t> t: class { ... public static t find(string idin) { return ... t; } }
now able specifiy return type in subclasses like
public class appletree:treemangement<appletree> { public string name; } public class orangetree:treemangement<orangetree> { public string name; } public class bananatree:treemangement<bananatree> { public string name; }
this way 3 find calls compile fine find()
call return correct type:
var savedappletree = appletree.find("somevalidid"); var savedorangetree = orangetree.find("somevalidid"); var savedbananatree = bananatree.find("somevalidid");
Comments
Post a Comment