mercredi 31 août 2016

FieldInfo.SetValue fails under certain circumatances

I am working on a QA testing framework for hardware devices tested by C# test programs. Part of running a compiled test is to use reflection on the compiled.exe to find where the Device-under-test (DUT) is declared in each test case and plug in the actual Framework-assigned device object.

Here is the heart of the code:

                    if (device.GetType().FullName.Equals(fi.FieldType.FullName))
                    {
                        try
                        {
                            fi.SetValue(tc, device);
                        }
                        catch (ArgumentException ex)
                        {
                            TestLogger.Warning(ex.Message);
                        }
                    }

In this code we already know from the first line that the 'device' is the same type as the field ('fi') in the test case ('tc').

Now the strange part: If the test case is in the same assembly as this code, everything is fine. If, however this code is part of a testing platform that loads the compiled test as an assembly, the call to SetValue() throws an ArgumentException with the message "Object of type 'X' cannot be converted to type 'X'" where X is the full name ofthe type of the device.

I have repeatedly searched both here and other sites for problem where SetValue() complained about inability to change one type to itself and the only instance I found involved serialization which is not a factor here.

QUESTION: What kind of problem could cause FieldInfo.SetValue() to balk like this when no conversion seems to be necessary?





Aucun commentaire:

Enregistrer un commentaire