IEntity上的Description / DescriptionFormatted()方法null引用异常

时间:2018-07-16 04:09:22

标签: c# mib sharp-snmp

我正在使用Sharpsnmp-pro来解析MIB文件。

从示例中,我有以下代码:

var registry = new SimpleObjectRegistry();
var collector = new ErrorRegistry();
registry.Tree.Collector = collector;
registry.Import(Parser.Compile(GetLocation("SNMPv2-SMI.txt"), collector));
registry.Import(Parser.Compile(GetLocation("SNMPv2-CONF.txt"), collector));
registry.Import(Parser.Compile(GetLocation("SNMPv2-TC.txt"), collector));
registry.Import(Parser.Compile(GetLocation("SNMPv2-MIB.txt"), collector));
registry.Import(Parser.Compile(GetLocation("SNMPv2-TM.txt"), collector));
registry.Refresh();

// get an item with a DESCRIPTION; this works fine...
Definition item = registry.Tree.Find("SNMPv2-MIB", "sysDescr");
IEntity entity = item.DisplayEntity;
Console.WriteLine(entity.DescriptionFormatted());


// now find an item without a DESCRIPTION; this raises null reference exception
item = registry.Tree.Find("SNMPv2-MIB", "snmpTrap");
entity = item.DisplayEntity;
Console.WriteLine(entity.DescriptionFormatted());

第二个调用引发空引用异常

   Object reference not set to an instance of an object.
   at Lextm.SharpSnmpPro.Mib.ObjectIdentifierMacro.쬯()
   at Lextm.SharpSnmpPro.Mib.EntityExtensions.DescriptionFormatted(IEntity entity)
   at snmptranslate.Program.Main(String[] args) 

如何在调用描述之前确定所讨论的实体是否具有描述,以避免使用空引用(最好不尝试try..catch捕获)?

例如,使用linq提取一个新实体以导出到Excel电子表格中,我希望DescriptionFormatted()只会返回空字符串,但失败。

var content = entities.Select(y => new { Module = y.Module.Name, y.Name, OID = y.GetObjectIdentifier(), Description = y.DescriptionFormatted() })

enter image description here

0 个答案:

没有答案