[.net] Associating a string with a type

Started by
3 comments, last by Numsgil 17 years, 4 months ago
This is probably pretty easy, but I'm not sure how to do it. I have a parser for a small, custom scripting language that represents DNA of virtual creatures. I have an interface called BasePair that the different DNA commands inherit from. What I want to do is create some sort of container that converts from strings to the implemented classes associated with that string, and vice versa. For instance, I have an "Add" class that inherits from my BasePair interface. I'd like to associate it with the string "add", so I can easily parse between the two. I'd also use this container to select random commands to insert for mutations. My initial try looks something like this:

BasePair Parse(string word)
{
  static SortedList<string, Type> mParser;

  return new mParser[word];


But the compiler doesn't like that at all. Any ideas? [Edited by - Numsgil on November 28, 2006 4:55:42 AM]
[size=2]Darwinbots - [size=2]Artificial life simulation
Advertisement
What does the compiler say ?
hi Numsgil,

you could try that

/* Base pair class */BasePair * BasePair::clone() = 0;/* Derived BasePair */BasePair * DerivedBP::clone(){  return ( new DerivedBP() );};/* you also have to add for each class one instance to mParser before use !!*/BasePair * Parse(string word){  static SortedList<string, Type> mParser;  return ( mParser[word].clone() );};


could work, actually sitting in work,
so you have to try, no time to check ;)

greets
tgar
Use System.Activator:

object CreateObject(string key){  return System.Activator.CreateInstance(mParser[key]);}


This will throw an exception if the type represented by mParser[key] cannot be default-constructed. CreateInstance() has overloads that can be used to pass values to the constructor if you want to enforce that, for example, the stored types have a constructor that takes a few ints:

object CreateObject(string key){  return System.Activator.CreateInstance(mParser[key],42,144,2808);}


Look up the documentation for System.Activator for more information.
@jpetrie: Yep, that was what I wanted. Thanks.
[size=2]Darwinbots - [size=2]Artificial life simulation

This topic is closed to new replies.

Advertisement