Setting a value through reflection does not work

I am trying to set a value through reflection. I created this little test program

    struct headerIndexes
    {
        public int AccountNum{ get; set; }
        public int other { get; set; }
        public int items { get; set; }
    }
    static void Main(string[] args)
    {

        headerIndexes headers = new headerIndexes();
        headers.AccountNum = 1;
        Console.WriteLine("Old val: {0}", headers.AccountNum);
        foreach (var s in headers.GetType().GetProperties())
        {
            if (s.Name == "AccountNum")
                s.SetValue(headers, 99, null);
        }
        Console.WriteLine("New val: {0}", headers.AccountNum);
        Console.ReadKey();
    }

When I run the program, I see it correctly, the command s.SetValue(headers, 99, null);, however the value of headers.AccountNum remains equal to 1 when running setValue.

Did I miss the obvious step?

+3
source share
3 answers

I think that headers can be placed in a new object, since it is a structure, and then the object gets garbage as soon as SetValue returns. Change it to a class and see if the problem goes away.

+3
source

SetValue object, headers. headers struct, . , , , - , headers.

.

:

, . .

+1

You can also use the unboxed version of struct.
unboxedHeader object = headers;
s.SetValue (unboxedHeader, 99, null);

struct headerIndexes 
{ 
    public int AccountNum{ get; set; } 
    public int other { get; set; } 
    public int items { get; set; } 
} 
static void Main(string[] args) 
{ 

    headerIndexes headers = new headerIndexes(); 
    headers.AccountNum = 1; 
    Console.WriteLine("Old val: {0}", headers.AccountNum); 
    object unboxedHeader=headers;
    foreach (var s in headers.GetType().GetProperties()) 
    { 
        if (s.Name == "AccountNum") 
            s.SetValue(unboxedHeader, 99, null); 
    } 
    Console.WriteLine("New val: {0}", headers.AccountNum); 
    Console.ReadKey(); 
} 
+1
source

Source: https://habr.com/ru/post/1727678/


All Articles