c# - Static method return an object of it's containing class type -
i have:
class person { public person(string name, int age) { this.name = name; } public string name { get; set; } public virtual void speak() { console.write("hello person"); } public static t generaterandominstance<t>() t: person { var p = new t("hello", 4); // error not compile // rondomize properties return p; } } class student : person { // constructor call base class here public student(string name, int age) : base(name, age) { } public override void speak() { console.write("hello student"); } }
the problem have when do:
student.generaterandominstance();
i person
instead of student
. how can fix generaterandominstance
method returns student instead of person. casting person student gives me error
you can't. static method cannot overridden in child class , there's no way distinguish between student.generaterandominstance
, person.generaterandominstance
—in fact generate same cil when compiled.
you use generic method instead:
public static t generaterandominstance<t>() t : person, new { var p = new t(); // randomize properties return p; } person.generaterandominstance<student>();
but work if type has parameterless constructor. if you'd pass arguments constructor, becomes more difficult. assuming know values want pass constructor can this:
public static t generaterandominstance<t>() t : person { var p = (t)activator.createinstance(typeof(t), "hello", 4); // randomize properties return p; }
of course, fail if specified type not contain suitable constructor.
Comments
Post a Comment