Sign in to follow this  
Numsgil

[.net] Associating a string with a type

Recommended Posts

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]

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this