mercredi 8 avril 2020

Can I call the "Set" method of a struct property using reflection?

I define a struct:

public struct Settable
{
     public string SettableProperty { get; set; }
}

I can set the value of the struct's property in the usual way:

s.SettableProperty = "Abc";

However, when I create a method to attempt to set the property by reflection:

public T CreateWithValue<T>(string propName, string propValue)
{
    var retObj = Activator.CreateInstance<T>();
    var prop = typeof(T).GetProperty(propName);

    var _ = prop.SetMethod.Invoke(retObj, new object[] { propValue});
    return retObj;
}

...and call it thus:

var x = CreateWithValue<Settable>("SettableProperty", "Abc");

...I end up with SettableProperty initialized to its default value, null. (No exception is thrown.)

Note that if I define Settable as a class instead of a struct, the value is set as expected.

Is it possible to set struct properties using reflection?





Aucun commentaire:

Enregistrer un commentaire