Using reflection to access and modify field values

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • samhng@gmail.com

    #1

    Using reflection to access and modify field values

    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(obje ct obj, string fieldName)
    {
    // print out the value of the given field name
    }
    }
    My question is what to do in the method printValue(obje ct, string)? Thx!

  • Joanna Carter [TeamB]

    #2
    Re: Using reflection to access and modify field values

    <samhng@gmail.c om> a écrit dans le message de news:
    1151483754.4101 74.287940@y41g2 00...legr oups.com...

    | 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(obje ct obj, string fieldName)
    | {
    | // print out the value of the given field name
    | }
    | }
    | My question is what to do in the method printValue(obje ct, string)? Thx!

    public void printValue(obje ct obj, string fieldName)
    {

    FieldInfo fi = obj.GetType().G etField(fieldNa me);

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

    Console.WriteLi ne(result);
    }

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

    Joanna

    --
    Joanna Carter [TeamB]
    Consultant Software Engineer


    Comment

    Working...