c# - How do I create a Dictionary of classes, so that I can use a key to determine which new class I want to initialize? -


as per question, how create dictionary in c# key say, integer, values classes can call constructor using value in dictionary? each of classes derived abstract class, , take same parameters, feel should able store resulting reference new class object in variable of abstract class type.

that being said, dictionary's value set filled references objects, not types themselves. quick example, here's i'm trying do:

abstract class baseobject {       int someint; }  class objecta : baseobject {      objecta (int number) {         someint = number;     } }   class objectb : baseobject {      objectb (int number) {         someint = number;     } } 

and want able following:

dictionary<int, ???????> objecttypes = new dictionary<int, ???????>();  objecttypes.add(0, objecta); objecttypes.add(1, objectb); 

so can eventually:

baseobject newobjecta, newobjectb;  newobjecta = new objecttypes[0](1000); newobjectb = new objecttypes[1](2000); 

the syntax quite different, hope @ least got across i'm trying accomplish.

are looking this?

var objecttypes = new dictionary<int, func<int, baseobject>>(); objecttypes[0] = input => new objecta(input); objecttypes[1] = input => new objectb(input);  objecttypes[0](1000); objecttypes[1](2000); 

here instead of storing object, store func generate each concrete object


Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -