我有一个不同类型对象的数组,我使用 BinaryWriter 将每个项目转换为其二进制等效项,以便我可以通过网络发送该结构。
我目前正在做类似的事情
for ( i=0;i<tmpArrayList.Count;i++)
{
object x=tmpArrayList[i];
if (x.GetType() == typeof(byte))
{
wrt.Write((byte)x);
}
........
问题是,如果错过了某个类型,我的代码将来可能会崩溃。
我想做类似的事情。
object x=tmpArrayList[i];
wrt.Write(x);
但除非我完成每个演员表,否则它不起作用。
Edit:
在咨询了答案之后,这就是我对该功能的想法。为了测试此函数将数组发送到系统日志。
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
}
不可以。必须在编译时知道强制转换,但实际类型只有在执行时才知道。
但请注意,有一种更好的方法可以调用 GetType 来测试类型。代替:
if (x.GetType() == typeof(byte))
Use:
if (x is byte)
编辑:回答额外的问题:
“都有哪些类型?”好吧,看看 BinaryWriter 的文档,我想......
“我需要担心字节和字节吗?”不,byte 是 C# 中 System.Byte 的别名。他们是同一类型。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)