Refelection - Dynamic programming

  • Thread starter Thread starter Nicky
  • Start date Start date
N

Nicky

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,
Nicky
 
// 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).

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
 
Hello,

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

FieldInfo fld = 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= System.Activator.CreateInstance(Type.GetType
(strobjectname));

and then

fld.SetValue(newobj ,objCollectie);

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

Do i mis somethin essential here?

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

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

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.
 
What I just wrote, is not good. In this case I have to
standalone objects and thats not what I want.

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

this.ObjectName must be dynamically, because somtimes it
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
 
Back
Top