Programmatic equivalent of default(Type)

2018-12-31 10: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 default(Type) explicitly, but I'd rather do it in one line. Is there a programmatic equivalent of default?

12条回答
素衣白纱
2楼-- · 2018-12-31 10:52

You can use PropertyInfo.SetValue(obj, null). If called on a value type it will give you the default. This behavior is documented in .NET 4.0 and in .NET 4.5.

查看更多
浮光初槿花落
3楼-- · 2018-12-31 10:55

The chosen answer is a good answer, but be careful with the object returned.

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

Extrapolating...

string test = GetDefault(typeof(string));
if (test is string)
     Console.WriteLine("This will never be hit.");
查看更多
浮光初槿花落
4楼-- · 2018-12-31 10:55

Equivalent to Dror's answer but as an extension method:

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;
        }
    }
}
查看更多
何处买醉
5楼-- · 2018-12-31 10:58

Can't find anything simple and elegant just yet, but I have one idea: If you know the type of the property you wish to set, you can write your own default(T). There are two cases - T is a value type, and T is a reference type. You can see this by checking T.IsValueType. If T is a reference type, then you can simply set it to null. If T is a value type, then it will have a default parameterless constructor that you can call to get a "blank" value.

查看更多
骚的不知所云
6楼-- · 2018-12-31 11:01
 /// <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;
    }
查看更多
十年一品温如言
7楼-- · 2018-12-31 11:06

Why do you say generics are out of the picture?

    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);
    }
查看更多
登录 后发表回答