Using reflection to access and modify field values

S

samhng

Hi,
Suppose I have a class:
public class Test
{
public string a;
public int b;
}
Now I want to access the value of variable a of the instance of the
class Test (@_@).
public class App
{
public static void Main(string[] args)
{
Test test = new Test();
test.a = "hello";
test.b = 3;

printValue(t, "a"); //print out the value of field a
}

public void printValue(object obj, string fieldName)
{
// print out the value of the given field name
}
}
My question is what to do in the method printValue(object, string)? Thx!
 
J

Joanna Carter [TeamB]

<[email protected]> a écrit dans le message de (e-mail address removed)...

| Suppose I have a class:
| public class Test
| {
| public string a;
| public int b;
| }
| Now I want to access the value of variable a of the instance of the
| class Test (@_@).
| public class App
| {
| public static void Main(string[] args)
| {
| Test test = new Test();
| test.a = "hello";
| test.b = 3;
|
| printValue(t, "a"); //print out the value of field a
| }
|
| public void printValue(object obj, string fieldName)
| {
| // print out the value of the given field name
| }
| }
| My question is what to do in the method printValue(object, string)? Thx!

public void printValue(object obj, string fieldName)
{

FieldInfo fi = obj.GetType().GetField(fieldName);

string result = (string) fi.GetValue(obj);

Console.WriteLine(result);
}

But you do realise that reflection is slower than accessing properties and
fields directly ?

Joanna
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top