我创建了以下属性,它抛出了一个InvalidCastException
if getter was 访问 when ViewState[TOTAL_RECORD_COUNT]
is null
。
public long TotalRecordCount
{
get { return (long)(ViewState[TOTAL_RECORD_COUNT] ?? -1); }
set { ViewState[TOTAL_RECORD_COUNT] = value; }
}
我的想法是它错误地尝试将对象拆箱ViewState[TOTAL_RECORD_COUNT]
到a 中,但int
失败了,因为它包含 a long
,但我认为该逻辑可能存在缺陷。我将把它作为练习留给读者指出这个缺陷。
从那以后,我将该属性更改为读取
public long TotalRecordCount
{
get { return (long?)ViewState[TOTAL_RECORD_COUNT] ?? -1; }
set { ViewState[TOTAL_RECORD_COUNT] = value; }
}
效果很好。不过,我仍然想知道我的原始版本出了什么问题...... StackOverflow 来救援?
请注意,如果我尝试(long)(ViewState[TOTAL_RECORD_COUNT] ?? -1)
在即时窗口中执行,我会收到错误消息Cannot unbox 'ViewState[TOTAL_RECORD_COUNT] ?? -1' as a 'long'
,如果我执行(ViewState[TOTAL_RECORD_COUNT] ?? -1).GetType().Name
,我会收到Int32
. 我可以执行(long)-1
并最终以 -1 作为Int64
...所以怎么了?