为什么DateTime的GetType不是常量值 [英] Why the GetType of DateTime is not a constant value
问题描述
Hi Folks,
我正在处理带有类型检查的switch语句..以下代码适用于所有类型,但是,挑战是使用Nullable类型。
I'm working on a switch statement with Type checking .. The following code is working perfectly well for all the types, but, the challenge is with Nullable types.
switch (Type.GetTypeCode( propertyInfos.PropertyType))
{
// Type code doesn't have reference with int, long, etc.,
case TypeCode.DateTime:
// Do the work for DateTime
break;
case TypeCode.Int32 :
// Do the work for Int32
break;
case TypeCode.Int64:
// Do the work for long
break;
case TypeCode.DateTime? :
break;
default:
break;
}
我试过将其更改为GetType和DateTime.Today.GetType()。ToString()会将System.DateTime作为字符串给出。但是,使用时,编译器会抛出错误,因为它不是有效的常量字符串。在任何给定的时间实例,DateTime.Today.GetType()
总是会给我们"System.DateTime",为什么编译器不接受这个?
I have tried that to change as GetType and DateTime.Today.GetType().ToString() would give us System.DateTime as a string. But, when used the compiler throws error as that is not a valid Constant string. At any given time instance, DateTime.Today.GetType() would always gives us "System.DateTime", why this is not accepted by compiler?
只要你分享,每件事情都是完美的
Every thing is perfect as long as you share
推荐答案
... ,但挑战是Nullable类型。
可以为空的'DateTime?'不是
TypeCode 枚举。因此,您的代码将导致语法错误。最好在对象进入switch语句之前检查null并抛出NullReferenceException。
The nullable 'DateTime?' is not a valid member of the TypeCode enumeration. So, your code will cause a syntax error. Better to check for null before your object enters the switch statement and throws a NullReferenceException.
wizend
这篇关于为什么DateTime的GetType不是常量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!