我使用反射来循环一个类型的属性,并将某些类型设置为默认值。现在,我可以在类型上进行切换,并显式地设置默认(type),但我宁愿在一行中完成。在编程中是否存在与默认设置相同的功能?


当前回答

为什么你说泛型被淘汰了?

    public static object GetDefault(Type t)
    {
        Func<object> f = GetDefault<object>;
        return f.Method.GetGenericMethodDefinition().MakeGenericMethod(t).Invoke(null, null);
    }

    private static T GetDefault<T>()
    {
        return default(T);
    }

其他回答

对@Rob Fonseca-Ensor的解决方案进行了轻微调整:下面的扩展方法也适用于. net Standard,因为我使用GetRuntimeMethod而不是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);
    }
}

...对于那些关心质量的人,相应的单元测试:

[Fact]
public void GetDefaultTest()
{
    // Arrange
    var type = typeof(DateTime);

    // Act
    var defaultValue = type.GetDefault();

    // Assert
    defaultValue.Should().Be(default(DateTime));
}

这应该可以工作: null <T> a = new Nullable<T>().GetValueOrDefault();

所选的答案是一个很好的答案,但要注意返回的对象。

string test = null;
string test2 = "";
if (test is string)
     Console.WriteLine("This will never be hit.");
if (test2 is string)
     Console.WriteLine("Always hit.");

推断……

string test = GetDefault(typeof(string));
if (test is string)
     Console.WriteLine("This will never be hit.");

如果是值类型,请使用Activator。CreateInstance,它应该可以正常工作。 当使用引用类型时,只返回null

public static object GetDefault(Type type)
{
   if(type.IsValueType)
   {
      return Activator.CreateInstance(type);
   }
   return null;
}

在。net的新版本,如。net标准中,键入。IsValueType需要被写成type.GetTypeInfo().IsValueType

为什么不调用带有反射返回default(T)的方法呢?你可以使用任何类型的GetDefault:

    public object GetDefault(Type t)
    {
        return this.GetType().GetMethod("GetDefaultGeneric").MakeGenericMethod(t).Invoke(this, null);
    }

    public T GetDefaultGeneric<T>()
    {
        return default(T);
    }