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


当前回答

您可以使用PropertyInfo。SetValue (obj, null)。如果在一个值类型上调用,它将为您提供默认值。这种行为在。net 4.0和。net 4.5中都有记录。

其他回答

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

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

相当于Dror的答案,但作为一种扩展方法:

namespace System
{
    public static class TypeExtensions
    {
        public static object Default(this Type type)
        {
            object output = null;

            if (type.IsValueType)
            {
                output = Activator.CreateInstance(type);
            }

            return output;
        }
    }
}

为什么不调用带有反射返回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);
    }
 /// <summary>
    /// returns the default value of a specified type
    /// </summary>
    /// <param name="type"></param>
    public static object GetDefault(this Type type)
    {
        return type.IsValueType ? (!type.IsGenericType ? Activator.CreateInstance(type) : type.GenericTypeArguments[0].GetDefault() ) : null;
    }