简体   繁体   中英

Convert enum? to int? fails when using reflection

It succeed when using int? to convert.
It failed when using reflection to convert.
How can I assign value enum? to property int? successful using reflection?

static void Main(string[] args)
{
    Dc dc = new Dc { Solution = Solution.Upgrade };

    Model model = new Model {  };

    //assign by reflection
    var psolution = model.GetType().GetProperty("Solution");
    //psolution.SetValue(model, dc.Solution); //this fail
    model.Solution = (int?)dc.Solution; //this success
    psolution.SetValue(model, Convert.ChangeType(dc.Solution, psolution.PropertyType)); //this fail
}

class Dc
{
    public Solution? Solution { get; set; }
}

class Model
{
    public int? Solution { get; set; }
}

enum Solution
{
    Upgrade = 1,
    Discard = 2,
}

Try this:

Type t = Nullable.GetUnderlyingType(psolution.PropertyType) ?? psolution.PropertyType;
object safeValue = (dc.Solution == null) ? null : Convert.ChangeType(dc.Solution, t);
property.SetValue(model, safeValue, null);

You need to get the underlying type parameter of Nullable<T> in order to set the value for the int? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM