Reputation: 1681
I was wondering if it was possible to referance a class field via variable. like so:
int variable = 0;
while (variable > 3)
{
class._fieldvariable = something;
i++
}
where if I have fields: _field1, _field2, _field3 I can iterate through them all.
The main reason for doing this is I have an sql query that will append multiple records and I'd rather not have to do all the parameters multiple times but rather something like this:
while (i < 4)
}
command.Parameters.AddWithValue("@Alpha1", _alphai01.ToString());
i++
}
to let me set parameters 3 times with _alpha101, _alpha201 and _alpha301 are used for three different queries.
thanks!
Upvotes: 2
Views: 124
Reputation: 1731
You could use reflection like this
if you have a class A
public class A
{
int field1, field2, field3;
}
you could set these fields like this
A obj = new A();
for (int i = 1; i < 4; i++)
{
FieldInfo field = obj.GetType().GetField(String.Format("field{0}", i), BindingFlags.NonPublic | BindingFlags.Instance);
if (null != field)
{
field.SetValue(obj, i);
}
}
Upvotes: 0
Reputation: 22624
Associate properties to the fields, all of them with get/set access.
If we're really talking about three fields, a more or less clean way to do so is by using a function GetField(int index)
which would return the corresponding property. Then your code can be
class.GetField(i) = something;
An array is better in the more general case (for example, if the number of fields is expected to change).
I would prefer not to use reflection for such a simple purpose.
Upvotes: 1
Reputation: 20899
You can use invokeMember
to call a certain setter of a property:
Object obj; //your instance;
obj.GetType().InvokeMember("Alpha1",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty,
Type.DefaultBinder, obj, "ValueForAlpha1");
that's equal to
obj.Alpha1 = "ValueForAlpha1";
http://msdn.microsoft.com/en-US/library/vstudio/66btctbe.aspx
Upvotes: 0