整理笔记 09-01-13

 

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);
            }
        }
    }

 

版权声明:本文为briskr原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/briskr/archive/2009/11/12/convert_changetype_nullable.html