c# - Generics of unknown type -
i'm creating settings class so:
class setting<t> {...}
i storing settings in tree so:
class settingsnode { public setting<> setting; public setting<> child; public setting<> sibling; }
this doesn't compile because of <>
. can have multiple types (setting<int>
, setting<string>
, etc) don't know how create settingsnode.
so changed to:
class settingsnode { public object setting; public object child; public object sibling; }
but having trouble casting right type:
// create setting type name text settingsnode tmp = new settingsnode(); type generictype = typeof(setting<>); type[] typeargs = { type.gettype("system.int32") }; type ctype = generictype.makegenerictype(typeargs); tmp.setting = activator.createinstance(ctype); // here's have problem type basetype = typeargs[0]; ((setting<basetype>)(tmp.setting)).somefunction();
the error on last line is:
the type or namespace name 'basetype' not found (are missing using directive or assembly reference?)
how can this? thanks!
one option can go ahead dynamic
keyword:
class settingsnode { public dynamic setting; public dynamic child; public dynamic sibling; }
so can this:
settingsnode tmp = new settingsnode(); tmp.setting = new setting<int>(); tmp.setting.somefunction()
without need using reflection
Comments
Post a Comment