有没有办法将对象强制转换回原始类型而不指定每个案例?

Rex*_*gan 2 c# casting syslog udpclient

我有一个不同类型对象的数组,我使用BinaryWriter将每个项目转换为二进制等价物,以便我可以通过网络发送结构.

我现在做的事情就像

for ( i=0;i<tmpArrayList.Count;i++)
{
   object x=tmpArrayList[i];
   if (x.GetType() ==  typeof(byte))
   {
      wrt.Write((byte)x);
   }
   ........
Run Code Online (Sandbox Code Playgroud)

问题是,如果错过了一个类型,我的代码将来可能会破坏.

我想做点什么.

object x=tmpArrayList[i];
wrt.Write(x);
Run Code Online (Sandbox Code Playgroud)

但除非我每次演员,否则它不起作用.

编辑:

在查阅答案之后,这就是我想出的功能.为了测试,该函数将数组发送到syslog.

  private void TxMsg(ArrayList TxArray,IPAddress ipaddress)
  {
     Byte[] txbuf=new Byte[0];
     int sz=0;

     // caculate size of txbuf
     foreach (Object o in TxArray)
     {
        if ( o is String ) 
        {
           sz+=((String)(o)).Length;
        }
        else if ( o is Byte[] )
        {
           sz+=((Byte[])(o)).Length;
        }
        else if ( o is Char[] )
        {
           sz+=((Char[])(o)).Length;
        }
        else // take care of non arrays
        {
           sz+=Marshal.SizeOf(o);
        }
     }
     txbuf = new Byte[sz];

     System.IO.MemoryStream stm_w = new System.IO.MemoryStream( txbuf, 0,txbuf.Length);
     System.IO.BinaryWriter wrt = new System.IO.BinaryWriter( stm_w );

     foreach (Object o in TxArray)
     {
        bool otypefound=false;
        if (o is String) // strings need to be sent one byte per char
        {
           otypefound=true;
           String st=(String)o;
           for(int i=0;i<st.Length;i++)
           {
              wrt.Write((byte)st[i]);
           }
        }
        else
        {
           foreach (MethodInfo mi in typeof(BinaryWriter).GetMethods())
           {
              if (mi.Name == "Write")
              {
                 ParameterInfo[] pi = mi.GetParameters();
                 if ((pi.Length == 1)&&(pi[0].ParameterType==o.GetType()))
                 {
                    otypefound=true;
                    mi.Invoke(wrt, new Object[] { o });
                 }
              }
           }
        }
        if(otypefound==false)
        {
           throw new InvalidOperationException("Cannot write data of type " + o.GetType().FullName);
        }
     }
     IPEndPoint endpoint = new IPEndPoint(ipaddress, 514); //syslog port
     UdpClient udpClient_txmsg = new UdpClient();
     udpClient_txmsg.Send(txbuf, txbuf.Length,endpoint); // send udp packet to syslog             
  }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

不可以.编译时必须知道强制转换,但实际类型只在执行时才知道.

但请注意,有一种更好的方法来测试调用GetType的类型.代替:

if (x.GetType() == typeof(byte))
Run Code Online (Sandbox Code Playgroud)

使用:

if (x is byte)
Run Code Online (Sandbox Code Playgroud)

编辑:回答额外的问题:

"这些类型是什么?" 好吧,看看BinaryWriter的文档,我猜......

"我需要担心字节和字节吗?" 不,byte是C#中System.Byte的别名.他们是同一类型.