A way to access/loop through variables within a struct or class?

  • Thread starter Thread starter Oliver
  • Start date Start date
O

Oliver

Hi there!

Does anyone know of a way on how you could access/loop through the variable
names. E.g. if you have a struct and want to loop through all variables in
that struct to give its value to the console?

Thanks in advance,
Oliver
 
207.46.248.16:

I just found out that problem is that I am using a struct and not a
class... so is this SetValue not supported for structs??
 
Oliver said:
I just found out that problem is that I am using a struct and not a
class... so is this SetValue not supported for structs??

No, effectively (at least, not as far as I can see). The thing is, when
you're passing in myStruct, you're passing in the *value* of myStruct,
not the variable itself. You need some way of passing it in by
reference. It's possible that SetValueDirect will allow you to do it,
but to be honest I can't easily figure out the way TypedReference
works.
 
@news.microsoft.com:

Hmm I thought that the problem is something like this. At the moment I am
trying this out. I also tried the SetValueDirect with no success... this
TypedReference is a bit confusing.

I will not give up :) mabye someone else knows the answer?

Thanks,
Oliver
 
Yipii I found the problem! Since I saw the only solution in SetValueDirect,
i tried to find a way to get it working by seeking informations on
TypedReference. And then I found the keyword -> __makeref <-
So all you have to do is write:

fi.SetValueDirect(__makeref(Test.MyField),"newvalue");

The __makeref command will give you the typed reference for the object:)

Thanks for your help,
Oliver
 
You can make the struct a 'ref' parameter to a method that must set
the fields on the struct. Then you can set all the fields you want
inside the method on its local copy, and when the method returns the
struct's overall value will be updated automatically for you (it won't
make any performance impact or logical difference if you passed a
class instance into that same method instead of a struct.)

If the struct is a field of a class you're processing in the method,
e.g. classInstance.Struct1 is how you access it, then you can use code
like this:

Field field;

// field is initialized to Struct1 of classInstance's Type
....

object obj = field.GetValue( classInstance );

// set fields of obj
....

if (obj.GetType().IsValueType) {
field.SetValue( classInstance, obj );
}

HTH
 
Back
Top