Groups | Blog | Home
all groups > c# > september 2003 >

c# : Refelection - Dynamic programming



Nicky
9/4/2003 11:43:57 PM
Hello,

I have to explain my problem with an example :

public class DecisionTables
{
public ObjectName ObjectName; // ObjectName defined in
other .cs
public DecisionTables()
{
functX();
}
public functX()
{
// Here I read from a database a name of an object and
put it in a string (normally in a loop)
string whichobject = "ObjectName";

// Create Instance of whichobject
Type collectieType = Type.GetType(whichobject );
Object objCollectie = System.Activator.CreateInstance
(collectieType);

// My problem : I will dynamically set the reference
of this new object to this.ObjectName.

// Not dynamically I do the following
this.ObjectName = (ObjectName)objCollectie;

// I don't want this, I think first I have to search for
a member in DecisionTables of the type ObjectName and then
I will give it a reference. But also the parsing must by
dynamically (I have to do the parsing).

}

Thanks,
Mattias Sjögren
9/5/2003 9:29:37 AM

[quoted text, click to view]

You can get a FieldInfo reference representing the
DecisionTables.ObjectName field with typeof(DecisionTables).GetField()
or .GetFields(). You can then assign objCollectie to it with
FieldInfo.SetValue().



Mattias

--
Mattias Sjögren [MVP] mattias @ mvps.org
http://www.msjogren.net/dotnet/
Nicky
9/8/2003 11:17:55 PM
Hello,

Thanks for the answer, but I still have a little problem.
I did the following and it works :

FieldInfo fld =3D typeof(DecisionTables).GetField
("ObjectName");
fld.SetValue(this.ObjectName ,objCollectie);


Only this.ObjectName is not dynamical.

Do I have to make an instance of it like this :
newobj=3D System.Activator.CreateInstance(Type.GetType
(strobjectname));

and then=20

fld.SetValue(newobj ,objCollectie);

Why instantiate a new object of it? In my not dynamically=20
example I did not instantiate the object:
this.ObjectName =3D (ObjectName)objCollectie;

Do i mis somethin essential here?

Thanks for help,
Nicky


[quoted text, click to view]
Nicky
9/8/2003 11:37:52 PM
What I just wrote, is not good. In this case I have to=20
standalone objects and thats not what I want.

Only in
fld.SetValue(this.ObjectName,objCollectie);

this.ObjectName must be dynamically, because somtimes it=20
can be this.ObjectName2 or this.ObjectName3 ....

like objcollectie depends of the string whichobject. alse
this.ObjectName depends if a string lest say Whichobject2.

Thanks in advance
[quoted text, click to view]
Jon Skeet
9/9/2003 7:32:03 AM
[quoted text, click to view]

That's very strange - you *should* be doing:

fld.SetValue (this, objCollectie);

You're setting the field within *this* object, not within the one
referred to by this.ObjectName. I'm very surprised that worked at all.

--
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet/
AddThis Social Bookmark Button