从 Type 获取默认值的最佳方法是什么

What is the best way of getting default value from Type

我有类型,我想获取默认值。例如,如果 Type 是 class 或可为 nullable,我应该得到 null。但如果它是整数,DateTime。十进制,...我应该得到 0。最好的方法是什么?

您可以使用Activator.CreateInstance生成一个空变量类型然后检查它的值:)

我希望你可以使用这样的东西:

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

Try it online

根据您的描述,您可以只使用 default expression or literal

int a = default(int);
int a = default;

Default values of C# types (C# reference)

Type Default value
Any reference type null
Anybuilt-in integral numeric type 0 (zero)
Any built-in floating-point numeric type 0 (zero)
bool false
char '[=15=]' (U+0000)
enum The value produced by the expression (E)0, where E is the enum identifier.
struct The value produced by setting all value-type fields to their default values and all reference-type fields to null.
Any nullable value type An instance for which the HasValue property is false and the Value property is undefined. That default value is also known as the null value of a nullable value type.