Jump to content
  • Advertisement
Sign in to follow this  
Numsgil

[.net] Associating a string with a type

This topic is 4254 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!