Programmatic equivalent of default(Type)

前端 未结 14 1495
时光取名叫无心
时光取名叫无心 2020-11-22 05:28

I\'m using reflection to loop through a Type\'s properties and set certain types to their default. Now, I could do a switch on the type and set the defau

相关标签:
14条回答
  • 2020-11-22 06:30

    This should work: Nullable<T> a = new Nullable<T>().GetValueOrDefault();

    0 讨论(0)
  • 2020-11-22 06:34

    Slight adjustments to @Rob Fonseca-Ensor's solution: The following extension method also works on .Net Standard since I use GetRuntimeMethod instead of GetMethod.

    public static class TypeExtensions
    {
        public static object GetDefault(this Type t)
        {
            var defaultValue = typeof(TypeExtensions)
                .GetRuntimeMethod(nameof(GetDefaultGeneric), new Type[] { })
                .MakeGenericMethod(t).Invoke(null, null);
            return defaultValue;
        }
    
        public static T GetDefaultGeneric<T>()
        {
            return default(T);
        }
    }
    

    ...and the according unit test for those who care about quality:

    [Fact]
    public void GetDefaultTest()
    {
        // Arrange
        var type = typeof(DateTime);
    
        // Act
        var defaultValue = type.GetDefault();
    
        // Assert
        defaultValue.Should().Be(default(DateTime));
    }
    
    0 讨论(0)
提交回复
热议问题