-2

我正在阅读一个文件,并逐行提供信息(这是我无法更改的)。如果该行具有 x 值并且如果该行具有 y 值,我想创建一个对象,则为该对象分配一些值。这被证明是非常具有挑战性的。显然我做错了什么。

if (line_split[i].Contains("LabelId"))
{
   try
   {
       gen.m_LabelId_pos.Add(multicast_ports[3], i);
       multicast my_multicast = new multicast();
   }
   catch
   {
   }
}
else if (line_split[i].Contains("TotalFrameSentCount_PerSecond"))
{
    try
    {                                    
        gen.m_TotalFrameSentCount_PerSecond_pos.Add(multicast_ports[3], i);
        // want to assign y value to the object here. but cant
    }
    catch
    {
    }
}
4

1 回答 1

3

您可以在语句之外声明对象if,在块中实例化它,并在检查它不是之后if在块中设置它的值。像这样的东西:elsenull

multicast my_multicast = null;
if (line_split[i].Contains("LabelId"))
{
   try
   {
       gen.m_LabelId_pos.Add(multicast_ports[3], i);
       my_multicast = new multicast();
   }
   catch
   {
   }
}
else if (line_split[i].Contains("TotalFrameSentCount_PerSecond"))
{
    try
    {                                    
        gen.m_TotalFrameSentCount_PerSecond_pos.Add(multicast_ports[3], i);
        if(my_multicast!=null)
        {
            //do something with my_multicast here
        }
    }
    catch
    {
    }
}

顺便说一句,你应该避免吃你的Exceptions,如果出现问题,它们是为了帮助你,这样 catch 块会隐藏它们,你不会知道出了什么问题。采用

catch(Exception err)
{
}
于 2012-12-03T23:51:49.110 回答