Convert.ChangeType() 方法转换时遇到 Nullable 的处理
整理笔记 09-01-13
- Nullable 属性需要转换赋值
-
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=95265
- PROBLEM: Imagine that Order has several nullabe types for properties.
-
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=95265
Order order = new Order(); foreach (System.Reflection.PropertyInfo prop in typeof(Order).GetProperties( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)) { object val = dr[prop.Name]; prop.SetValue(order, val == DBNull.Value ? null : Convert.ChangeType(val, prop.PropertyType), null); }
I initially tried w/o the ChangeType call, but neither work.
- SOLUTION (for Whidbey beta)
using System; class Order { public int Expenses { set { } } public int? Income { set { } } } class Program { public static Object HackType(object val, Type targetType) { // If target type is generic and Nullble<> // Who knows ? Possibly structs will be allowed to inherit if (targetType.HasGenericArguments && targetType.GetGenericTypeDefinition().Equals(typeof(Nullable<>))) { // Get argument type for Nullable<T> Type baseType = targetType.GetGenericArguments()[0]; // If original obj was a Nullable-like already - unwrap if (val is INullableValue) { if (((INullableValue)val).HasValue) { val = ((INullableValue)val).Value; } else { val = null; } } // Change type and wrap return Nullable.Wrap(Convert.ChangeType(val, baseType), baseType); } else { return Convert.ChangeType(val, targetType); } } static void Main(string[] args) { Order order = new Order(); foreach (System.Reflection.PropertyInfo prop in typeof(Order).GetProperties( System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance)) { object val = 10; prop.SetValue(order, HackType(val, prop.PropertyType), null); } } }
- http://blogs.msdn.com/haibo_luo/archive/2005/08/23/455241.aspx
- http://blogs.msdn.com/somasegar/archive/2005/08/11/450640.aspx about the DCR (Design Change Request)
typeof(Nullable<>).MakeGenericType(someValueType)
版权声明:本文为briskr原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。