object from string

  • Thread starter Thread starter Charles E. Vopicka
  • Start date Start date
C

Charles E. Vopicka

my first question is simple. can i do it? the second is more
dificult potentialy. how?

so here it is...

i need to read in a string and create a button. so if the
initialization file said "button1" then a button called button1 would
be created. if things were easy then i would think something like

object("button1") = new button

then be able to do stuff like

object("button1").text = "Stuff"

is this possable or do i need to create a whole bunch of buttons then
make them when i need them. i only used a button as an example but i
will also need labels and textboxes. i assume that if i can do one i
can do the rest. but i don't want to create a lot of declarations
when not all of the items may be used.

then the second part is how do i do this if it is possable.

thanks for any help you can offer.
 
Charles said:
my first question is simple. can i [create an object from a string]?
the second is more dificult potentialy. how?

Sounds like you're asking for something like an eval function like you'd
find in JavaScript, right. In a scripting environment that is a
reasonable approach, but it comes at pretty high cost (late binding and
so on.)

In a compiled language there are better ways to solve the problem. Try
using a .NET Framework collection class like one of the Dictionary
classes to map from strings to objects. Here's a minimal example that
returns real Buttons instance instead of just objects.


using System;
using System.Collections.Specialized;
using System.Windows.Forms;

class ButtonDictionary
{
private HybridDictionary buttons = new HybridDictionary();

public void Add( string name, Button button )
{ buttons.Add( name, button ); }

// Indexer (use overloaded Item property in VB)
public Button this[ string name ]
{ get { return (Button) buttons[ name ]; } }
}


Here is some code showing ButtonDictionary in use.


void Test()
{
ButtonDictionary buttons = new ButtonDictionary();

// create some buttons, add them to
buttons.Add( "curly", new Button() );
buttons.Add( "moe", new Button() );
buttons.Add( "larry", new Button() );

// find moe
buttons[ "moe" ].Text = "Oh, wise guy, eh?";
}


ButtonDictionary is pretty compact, so there is little problem creating
other strongly-typed collections for other types (ListBoxDictionary,
etc.)

Cheers,
Stuart Celarier, Fern Creek
 
Back
Top