// 获取某个定长字段 protected VariableLengthField GetVariableField(string id) { VariableLengthField temp = null; foreach (VariableLengthField field in this.VariableLengthFields) { if (field.ID == id) { //return field; temp = field;//2020/8/13 改造,找到最后一个同名字段再返回。 } } return(temp); }
// 将对象转换字符串命令 public virtual string ToText() { Debug.Assert(String.IsNullOrEmpty(this.CommandIdentifier) == false, "命令指示符未赋值"); StringBuilder text = new StringBuilder(this.CommandIdentifier); if (this.FixedLengthFields != null) { //foreach (FixedLengthField field in this.FixedLengthFields) for (int i = 0; i < this.FixedLengthFields.Count; i++) { FixedLengthField field = this.FixedLengthFields[i]; if (field.Value == null || field.Value.Length != field.Length) { throw new Exception("定长字段[" + field.Name + "]的值为null或者长度不符合定义"); } text.Append(field.Value); } } if (this.VariableLengthFields != null && this.VariableLengthFields.Count > 0) { //foreach (VariableLengthField field in this.VariableLengthFields) for (int i = 0; i < this.VariableLengthFields.Count; i++) { VariableLengthField field = this.VariableLengthFields[i]; if (field.Value != null) { text.Append(field.ID + field.Value + SIPConst.FIELD_TERMINATOR); } } } string result = text.ToString(); // 去掉字符串最后一个| if (string.IsNullOrEmpty(result) == false) { if (result.Substring(result.Length - 1) == SIPConst.FIELD_TERMINATOR) { result = result.Substring(0, result.Length - 1); } } return(result); }
protected string GetVariableFieldValue(string id) { VariableLengthField field = this.GetVariableField(id); if (field == null) { // 20170811 jane todo if (id == "AY" || id == "AZ") { return(""); } throw new Exception("未定义变长字段" + id); } return(field.Value); }
// 设置某个定长字段的值 protected void SetVariableFieldValue(string id, string value) { VariableLengthField field = this.GetVariableField(id); if (field == null) { // 20170811 jane todo if (id == "AY" || id == "AZ") { return; } throw new Exception("未定义变长字段" + id); } // 2020/8/13 如果是重复的字段,先检查字段是否已经赋值,没赋值过则赋值, // 如果已有值,则新new的一个字段,插在其后(这样可以保证原始的字段顺序) if (field.IsRepeat == false) { field.Value = value; } else { if (string.IsNullOrEmpty(field.Value) == true) { field.Value = value; } else { VariableLengthField f = new VariableLengthField(id, field.IsRepeat, field.IsRepeat); f.Value = value; // 插在其后,不要用增加(这样可以保证原始的字段顺序) this.VariableLengthFields.Insert(this.VariableLengthFields.IndexOf(field) + 1, f); //this.VariableLengthFields.Add(f); } } }