how to get the default value of a type if the type is only known as System.Type? [duplicate]

徘徊边缘 提交于 2019-11-27 19:59:39

Since you really only have to worry about value types (reference types will just be null), you can use Activator.CreateInstance to call the default constructor on them.

public static object GetDefaultValue(Type type) {
   return type.IsValueType ? Activator.CreateInstance(type) : null;
}

Edit: Jon is (of course) correct. IsClass isn't exhaustive enough - it returns False if type is an interface.

Here is how I normally do it. This avoids the whole 'IsValueType' or searching for constructors issues altogether.

public static object MakeDefault(this Type type)
{
    var makeDefault = typeof(ExtReflection).GetMethod("MakeDefaultGeneric");
    var typed = makeDefault.MakeGenericMethod(type);
    return typed.Invoke(null, new object[] { });
}

public static T MakeDefaultGeneric<T>()
{
    return default(T);
}

Without a generic, you can't guarantee that the type has a parameterless constructor, but you can search for one using reflection:

public static object GetDefaultValue(Type type)
{
    ConstructorInfo ci = type.GetConstructor( new Type[] {} );
    return ci.Invoke( new object[] {} );
}

I tried this in a console app, and it returns a "default" instance of the class — assuming it's a class. If you need it to work for reference types as well, you'll need an additional technique.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!