为了账号安全,请及时绑定邮箱和手机立即绑定

转换枚举?诠释?使用反射时失败

转换枚举?诠释?使用反射时失败

C#
红颜莎娜 2021-05-04 15:50:34
使用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 回答

?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

试试这个:


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?。


查看完整回答
反对 回复 2021-05-16
  • 1 回答
  • 0 关注
  • 127 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信