开发者

Nullables? Detecting them

Ok, im still a bit new to using nullable types.

I'm writing a reflecting object walker for a project of mine, im getting to the point where im setting the value of a reflected property with the value i've retrieved from a reflected property.

The value i've retrieved is st开发者_高级运维ill in object form, and it dawned on me, since i want my object walker to return null when it can't find something, (I thought about throwing an exception, but i want this to soft-fail when something's wrong).

Anyway, some of the values im setting/getting are decimal bool etc... so it dawned on me that i should just NOT set a non-nullable value, but I realized I straight up don't know how to tell decimal from decimal?

Is it enough to key on if the Type of the property im setting is inherited from ValueType?


The following code will tell you whether a type is nullable or not:

private bool IsNullableType(Type theType)
{
    return theType.IsGenericType && 
           theType.GetGenericTypeDefinition().Equals(typeof(Nullable<>));
}


From MSDN:

Nullable types are instances of the System.Nullable<T> struct.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜