转换枚举?到int?使用反射时失败

时间:2018-04-26 07:50:49

标签: c# reflection

使用int?转换时成功 使用反射转换时失败 如何使用反射成功将值enum?分配给属性int?

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,
}

1 个答案:

答案 0 :(得分:3)

试试这个:

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

您需要获取Nullable<T>的基础类型参数才能设置int?的值。