.NET - Get default value for a reflected PropertyInfo

前端 未结 6 1706
鱼传尺愫
鱼传尺愫 2020-12-08 02:02

This is really stumping me today. I\'m sure its not that hard, but I have a System.Reflection.PropertyInfo object. I want to set its value based on the result of a database

6条回答
  •  鱼传尺愫
    2020-12-08 02:30

    This is a more polished version that maintains the .NET Runtime's functionality without adding any unnecessary custom code.

    NOTE: This code written for .NET 3.5 SP1

    namespace System {
    
    public static class TypedDefaultExtensions {
    
        public static object ToDefault(this Type targetType) {
    
            if (targetType == null)
                throw new NullReferenceException();
    
            var mi = typeof(TypedDefaultExtensions)
                .GetMethod("_ToDefaultHelper", Reflection.BindingFlags.Static | Reflection.BindingFlags.NonPublic);
    
            var generic = mi.MakeGenericMethod(targetType);
    
            var returnValue = generic.Invoke(null, new object[0]);
            return returnValue;
        }
    
        static T _ToDefaultHelper() {
            return default(T);
        }
    }
    

    }

    USAGE:

    PropertyInfo pi; // set to some property info
    object defaultValue = pi.PropertyType.ToDefault();
    
    public struct MyTypeValue { public int SomeIntProperty { get; set; }
    var reflectedType = typeof(MyTypeValue);
    object defaultValue2 = reflectedType.ToDefault();
    

    Rashad Rivera (OmegusPrime.com)

提交回复
热议问题