如果只有类型被称为System.Type,如何获取类型的默认值? [英] how to get the default value of a type if the type is only known as System.Type?

查看:308
本文介绍了如果只有类型被称为System.Type,如何获取类型的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想要一个方法返回给定类型的默认值,并且方法是泛型的,那么可以返回默认值,如下所示:

If I want a method that returns the default value of a given type and the method is generic I can return a default value like so:

public static T GetDefaultValue()
{
  return default(T);
}

我可以做类似的事情吗? c $ c $> System.Type object?

Can I do something similar in case I have the type only as a System.Type object?

public static object GetDefaultValue(Type type)
{
  //???
}


推荐答案

担心值类型(引用类型只会为空),您可以使用 Activator.CreateInstance 来调用它们的默认构造函数。

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;
}

编辑:Jon(当然)是正确的。 IsClass 不够详尽 - 它会返回 False if type 是一个接口。

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

这篇关于如果只有类型被称为System.Type,如何获取类型的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆