c# - Dynamically create base class or inherited class -
title may not trying do. not sure if possible, maybe there workaround. code below try show want achieve, know wrong. possible create base class or inherited class @ runtime? or achieve goal somehow else? hope main idea code. if not, i'll try explain more.
public class baseclass { public int basenumber {get; set;}; } public class derivecclass : baseclass { public int derivednumber {get; set;}; } public baseclass foo(bool derived) { var classinstance; if (derived) { classinstance = new derivedclass(); } else { classinstance = new baseclass(); } classinstance.basenumber = 1234; if (derived) { classinstance.derivednumber = 4321; } return classinstance; }
you can't "rebase" class @ runtime (and implicitly classes subclass class or system.object
(that class :-) )
you can create @ runtime new dynamic classes through system.reflection.emit
namespace. need use typebuilder class. new classes can subclass class isn't sealed , doesn't have private
/internal
constructor (there special exceptions)
if want simple factory pattern, easy:
public class baseclass { public int basenumber { get; set; } // baseclass can't created other code through // new baseclass() protected baseclass() { } public static baseclass create(bool derived) { baseclass classinstance; if (derived) { classinstance = new derivedclass(); } else { classinstance = new baseclass(); } classinstance.basenumber = 1234; if (derived) { ((derivedclass)classinstance).derivednumber = 4321; } return classinstance; } } public class derivedclass : baseclass { public int derivednumber { get; set; } // derivedclass can't created other code through // new derivedclass() protected derivedclass() { } }
this pattern, written, used xmlreader.create(string, xmlreadersettings)
Comments
Post a Comment