任何类型的默认值。 [英] Default value of any type.

查看:77
本文介绍了任何类型的默认值。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于任何给定的类型,我想知道它的默认值。


有一个简洁的关键字叫默认,就像这样做

object x = default (DateTime);

但我有一个Type的实例(称为someType)和类似

这样的工作无法工作

object x = default( someType);


有什么好办法吗?我真的不想写一个

巨大的开关块,列举.NET中的所有类型!

For any given type i want to know its default value.

There is a neat keyword called default for doing this like
object x = default(DateTime);
but I have an instance of Type (called someType) and something like
this cant work
object x = default(someType);

Is there any nice way of doing this? I dont really want to write a
huge switch block enumerating all types in .NET !

推荐答案

泛型可能会有所帮助,因为默认(T)可以正常工作......

如果这不是一个选项,你可以让生活变得更简单:只有

值-types具有非null结果,value-types具有默认值

ctor(kind-of) - 所以:


object obj = type。 IsValueType?

Activator.CreateInstance(type):

obj = null;


注意,因为它是盒装的,对于Nullable< ; Tyou会得到null,而不是一个盒装的空值 - 这可能是你想要的。


Marc
Generics might help, since default(T) will work fine...
If this isn''t an option, you can make life a little simpler: only
value-types have a non-null result, and value-types have a default
ctor (kind-of) - so:

object obj = type.IsValueType ?
Activator.CreateInstance(type) :
obj = null;

Note that since it is boxed, for Nullable<Tyou will get null, not an
boxed empty value - which is probably what you want anyway.

Marc


(复制粘贴故障 - 应该已经读过:)


object obj = type.IsValueType?

Activator.CreateInstance(type): null;
(copy paste glitch - should have read:)

object obj = type.IsValueType ?
Activator.CreateInstance(type) : null;


11月14日上午11:00,GeezerButler< kurtr ... @ gmail.comwrote:
On Nov 14, 11:00 am, GeezerButler <kurtr...@gmail.comwrote:

对于任何给定的类型,我想知道它的默认值。


有一个简洁的关键字叫默认,就像这样做

对象x =默认(DateTime);

但我有一个Type的实例(称为someType)和类似

这样的工作无法工作

对象x =默认(someType);


有什么好办法吗?我真的不想写一个

巨大的开关块枚举.NET中的所有类型!
For any given type i want to know its default value.

There is a neat keyword called default for doing this like
object x = default(DateTime);
but I have an instance of Type (called someType) and something like
this cant work
object x = default(someType);

Is there any nice way of doing this? I dont really want to write a
huge switch block enumerating all types in .NET !



对于值类型,您始终可以使用Activator.CreateInstance(someType)

,因为它们保证是无参数构造函数。

对于引用类型,默认值始终为null。

您可以使用Type.IsValueType来区分。


Jon

For value types, you can always use Activator.CreateInstance(someType)
as there''s guaranteed to be a parameterless constructor.
For reference types, the default value is always null.

You can tell the difference using Type.IsValueType.

Jon


这篇关于任何类型的默认值。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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