获取默认值(T)给定类型代表T [英] Get default(T) given Type representing T

查看:105
本文介绍了获取默认值(T)给定类型代表T的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好:


我想获得默认(T)。但是,我不知道T是什么,直到

运行时;我只有一个类型。有没有一种方法可以获得默认(T)的结果




谢谢,

Travis

解决方案

2008年8月29日星期五11:28:39 -0700, je ********** @ gmail.com

< je ********** @ gmail.comwrote:


你好:


我想得到默认值(T)。但是,我不知道T是什么,直到

运行时;我只有一个类型。有没有一种方法可以获得默认(T)的结果




你能更具体一点吗?通常,您可以只写default(T)

,其中T是您的泛型类型的类型参数,它将起作用。


假设那个'不适合你,如果你能解释原因,那将是有用的。你在做什么导致

方法失败?一些示例代码会有所帮助。


Pete




< je ***** *****@gmail.com在留言中写道

新闻:f6 **************************** ****** @ 8g2000hs e.googlegroups.com ...


您好:


我想要得到默认值(T)。但是,我不知道T是什么,直到

运行时;我只有一个类型。有没有一种方法可以获得默认(T)的结果




它有点含糊不清。如果T是一个类型参数,那么默认(T)_是_

答案。


如果T只是你未知T的地方标记那么它是怎么回事未知?

是否要为对象类型引用的对象类型创建默认值




更多的代码可以帮助指导我们吗?

-

Anthony Jones - MVP ASP / ASP.NET


我在运行时这样做。如果它是在编译时,我会直接使用T $




我有一个Type实例。我想模仿默认(T)提供的功能

。这会有用吗:


if(type.IsValueType)

{

返回Activator.CreateInstance(type);

}

其他

{

返回null;

}

Hello:

I would like to get default(T). However, I don''t know what T is until
runtime; I just have a Type. Is there an equivilent means of getting
the results of default(T)?

Thanks,
Travis

解决方案

On Fri, 29 Aug 2008 11:28:39 -0700, je**********@gmail.com
<je**********@gmail.comwrote:

Hello:

I would like to get default(T). However, I don''t know what T is until
runtime; I just have a Type. Is there an equivilent means of getting
the results of default(T)?

Could you be more specific? Generally, you can just write "default(T)"
where T is the type parameter for your generic type and it will work.

Taking as an assumption that that''s _not_ working for you, it would be
helpful if you could explain why. What are you doing that causes that
approach to fail? Some sample code would help.

Pete



<je**********@gmail.comwrote in message
news:f6**********************************@8g2000hs e.googlegroups.com...

Hello:

I would like to get default(T). However, I don''t know what T is until
runtime; I just have a Type. Is there an equivilent means of getting
the results of default(T)?

Its a little ambiguous. If T is a type parameter then default(T) _is_ the
answer.

If T is simply a place marker for your unknown T then how is it unknown?
Do you want to create a default value for the type of an object referenced
by an object type?

A bit more code would help direct us?
--
Anthony Jones - MVP ASP/ASP.NET


I am doing this at runtime. If it was at compile time, I would just
use T directly.

I have an instance of Type. I would like to emulate the functionality
that default(T) provides. Would this work:

if (type.IsValueType)
{
return Activator.CreateInstance(type);
}
else
{
return null;
}


这篇关于获取默认值(T)给定类型代表T的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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