Home > 计算机与 Internet > C#: short+short->int 导致 “对象的当前状态使该操作无效”

C#: short+short->int 导致 “对象的当前状态使该操作无效”

Err:使用short数组加上偏移量写入short类型的索引缓冲IndexBuffer,引发“对象的当前状态使该操作无效”异常。
错误原因如下:
“以下赋值语句将产生一个编译错误,原因是赋值运算符右侧的算术表达式默认情况下计算为int”——MSDN
short x=1, y=2;
short z = x + y; //编译Err
 
在重载short/int的方法参数中直接传入上述表达式不会导致编译错误,但将调用错误的方法,下面的语句:
   short[] indexArray;
   short offset;
   //……
   using(GraphicsStream gs = m_indexBuffer.Lock(0, sizeof(short) * indexLength, LockFlags.None))
   {
       for (int i = 0; i < indexLength; i++)
      {
           gs.Write(indexArray[i] + offset); // 导致运行时错误:"对象的状态使得该操作无效" 
      }
   }
   //……
 
修正:
        {
            short iTmp = (short)(indexArray[i] + offset);
            gs.Write(iTmp); 
        }
 
类型安全…看来再安全的地方都有陷阱啊…喝水都有呛死的…
Advertisements
Categories: 计算机与 Internet
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: