c# - Create new instance of a class, using a string -
i making game in xna , have been trying find way create class using string. want work this:
string classtype = "drilltool"; //classtype/classname invitem item = new .... ("drilltool"); //this i'm lost!
the drilltool class looks this:
class drilltool : invitem //the constructor public drilltool(string itemname, string spritename, string storedbatterypower etc.)
so question is: how create new instance of class, using string? , how can pass in parameters or "constructor values" newly created class
detailes below here:
the myclass class inherits invitem (inventoryitem) class, can maintain different classes in same list, since should items. items divided in different classes because want them have different abilities/values , commands.
another question: how cast class own type/class without if statements?
like this:
invitem drillitem = new drilltool(etc.); (typeof(drillitem))drillitem.valuethatonlyexistsindrilltoolclass; //? //i can't access drilltool values of drillitem if has not been "converted".
and not this:
if (drillitem.gettype() == typeof(drilltool)) { currentitem = (drilltool)drillitem; currentitem.valuethatonlyexistsindrilltoolclass; } else if (etc.) //i gonna end on 20 classes @ least.
if unclear somewhere or if need more information, tell what's needed.
any help appreciated. in advance.
if have this, doing wrong!
ok, said; need overload of activator.createinstance
(msdn)
type mytype = type.gettype(typestring); object obj = activator.createinstance(mytype, myargs, "myotherstringargs");
i don't understand sec question; cast work:
drilltool tool = (drilltool)obj;
of course, throw if cast invalid. need if statements (using is
or typeof
) avoid exceptions. can utilize this:
drilltool tool = obj drilltool;
which homecoming null
if cast fails.
you cannot cast "dynamic" type (without using dynamic
keyword). behavior not supported/allowed in .net. reasoning should obvious; if string different, , resulting type doesn't have special property? .net tries hard type safe, , behavior type-safe.
you seem encountering pain of doing this; should indicator of first sentence. you shouldn't ever this. there few valid utilize cases; sincerely uncertainty have 1 of them.
c# xna
No comments:
Post a Comment