mardi 14 juin 2016

C# Field Reflection not working

I'm trying to get reflection to work on a field I have for an object called "Name". "Name" is a public string field variable (not property) in the class SPConfiguration. I iterate through a JSON dictionary and get the field keys and values e.g. {"Name", "NewName"}. Here is my code:

    foreach (var field in newFields)
    {
        Console.WriteLine("\n\n\n");
        Console.WriteLine("field is: " + field);
        Console.WriteLine("field value is: " + field.Value);
        Console.WriteLine("field key is: " + field.Key);

        Type myType = typeof(SPConfiguration);
        FieldInfo myFieldInfo = myType.GetField(field.Key);
        Console.WriteLine("Value before: " + myFieldInfo.GetValue(configToUpdate));
        myFieldInfo.SetValue(configToUpdate, "Woooo");
        Console.WriteLine("Value after: " + myFieldInfo.GetValue(configToUpdate));
}

The print statements in the foreach loop print:

field is: [Name, NewNameTest]
field value is: NewNameTest
field key is: Name
value before: MF_Test
value after: MF_Test

I expect the value of Name to be "NewNameTest" after running my code but as you can see it isn't changing. Changing 'Name' the normal way (.Name = "NewNameTest") works perfectly fine but I need to do this with reflection. Any ideas for what I'm doing wrong?

EDIT: SPConfiguration is not the Share Point configuration class - it's a custom class. Turns out SPConfiguration is actually a struct not a class. I completely missed/overlooked this - going to search how to perform reflection on structs now.





Aucun commentaire:

Enregistrer un commentaire