使用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?。
- 1 回答
- 0 關注
- 166 瀏覽
添加回答
舉報
0/150
提交
取消