问题描述
令人惊讶的是下面的代码失败的断言:
Surprisingly the following code fails the Assert:
int? wtf = 0;
Assert.IsType<Nullable<int>>(wtf);
所以,只是出于好奇,你怎么能确定给定的实例是一个可空<>对象与否?
So just out curiosity, how can you determine if a given instance is a Nullable<> object or not?
推荐答案
那么首先,可空< T>
是一个结构,所以没有一个的对象的本身。你不能叫的GetType()
,因为这将框中的值(此时你要么空,因此异常,或者一个盒装非空的值,因此。不是你想要的类型)
Well firstly, Nullable<T>
is a struct, so there isn't an object as such. You can't call GetType()
, as that will box the value (at which point you either get null and thus an exception, or a boxed non-nullable value and therefore not the type you want).
(拳击是怎么在这里搞乱你的断言 - 我假设 IsType
接受对象
)
(Boxing is what's messing up your assertion here - I would assume that IsType
accepts object
.)
您可以使用类型推断,虽然得到的类型的变量作为类型参数:
You can use type inference though to get the type of the variable as a type parameter:
public bool IsNullable<T>(T value)
{
return Nullable.GetUnderlyingType(typeof(T)) != null;
}
这是当你知道在之前编制的确切类型不是一个巨大的使用量时间在你的榜样,但它是仿制药有用。 (有实现它,当然的替代方式。)
That's not a huge amount of use when you know the exact type at compile-time as in your example, but it's useful for generics. (There are alternative ways of implementing it, of course.)
什么是你的真实生活状况?我认为这不是一个像这样的说法,因为你知道答案,这一个在编译时。
What's your real life situation? I assume it's not an assertion like this, given that you know the answer to this one at compile time.
这篇关于通过检测反射可空类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!