如何在#SNMP中检查ObjectIdentifier是否为另一个的根/父标识符?
在#SNMP组件中检查ObjectIdentifier的根/父标识符关系
确实,#SNMP组件里并没有直接提供IsRootOf这类现成方法,但我们可以利用ObjectIdentifier类的内置属性自己实现这个逻辑——OID本质就是一组有序的整数序列,判断根/父关系核心就是做前缀匹配。
先明确两个概念
- 根标识符:目标OID以当前OID为完整前缀,且目标OID的长度更长(比如
1.3.6是1.3.6.1.2的根) - 直接父标识符:目标OID的长度正好比当前OID长1,且完全匹配当前OID的所有前缀组件(比如
1.3.6是1.3.6.1的直接父,但不是1.3.6.1.2的父)
实现扩展方法
我们可以给ObjectIdentifier写两个扩展方法,分别实现这两种判断逻辑:
using System; using System.Collections.Generic; using Lextm.SharpSnmpLib; public static class ObjectIdentifierExtensions { /// <summary> /// 检查当前OID是否是目标OID的根标识符(包含多级子项) /// </summary> public static bool IsRootOf(this ObjectIdentifier current, ObjectIdentifier target) { if (current == null) throw new ArgumentNullException(nameof(current)); if (target == null) throw new ArgumentNullException(nameof(target)); IList<int> currentParts = current.Components; IList<int> targetParts = target.Components; // 根OID的长度必须小于目标OID,否则不可能是根 if (currentParts.Count >= targetParts.Count) return false; // 逐个匹配前缀组件 for (int i = 0; i < currentParts.Count; i++) { if (currentParts[i] != targetParts[i]) return false; } return true; } /// <summary> /// 检查当前OID是否是目标OID的直接父标识符 /// </summary> public static bool IsParentOf(this ObjectIdentifier current, ObjectIdentifier target) { if (current == null) throw new ArgumentNullException(nameof(current)); if (target == null) throw new ArgumentNullException(nameof(target)); IList<int> currentParts = current.Components; IList<int> targetParts = target.Components; // 父OID的长度必须正好比目标OID短1 if (currentParts.Count != targetParts.Count - 1) return false; // 完全匹配所有前缀组件 for (int i = 0; i < currentParts.Count; i++) { if (currentParts[i] != targetParts[i]) return false; } return true; } }
用法示例
就像你期望的那样直接调用即可:
ObjectIdentifier rootId = new ObjectIdentifier("1.3.6.1"); Variable variable = ...; // 从SNMP响应中获取的变量 if (rootId.IsRootOf(variable.Id)) { // 该变量的ID是根ID的子项(包括所有多级子OID) } // 如果要检查直接父关系 if (rootId.IsParentOf(variable.Id)) { // 该变量的ID是根ID的直接子项 }
注意事项
- 别忘了处理
null情况,避免空引用异常 - 如果需要更宽松的匹配(比如允许根OID和目标OID长度相等,即自身),可以修改
IsRootOf里的长度判断条件为currentParts.Count <= targetParts.Count
内容的提问来源于stack exchange,提问作者Vapid
相关产品推荐
相关产品推荐

