using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using TrainInfomationProviderService.StationInfo; using TrainInfomationProviderService.StationInfo.Entities; namespace TrainInfomationProviderService.TrainInfo.Entities { public class Train : IEquatable { /// /// ID /// [JsonProperty("i")] public string Id { get; set; } /// /// 列车编号 /// [JsonProperty("c")] public string Code { get; set; } /// /// 发站 /// [JsonProperty("f")] public string From { get; set; } /// /// 到站 /// [JsonProperty("t")] public string To { get; set; } [JsonProperty("s")] public List TrainStops { get; set; } [JsonIgnore] public Dictionary TrainStopMap { get; private set; } string _trainHash; [JsonIgnore] public string TrainHash { get { if (string.IsNullOrEmpty(_trainHash)) { _trainHash = CalculateTrainHash(); } return _trainHash; } } string CalculateTrainHash() { var data= Id + Code + TrainStops.Select(s => s.Code + (s.Arrive == null ? "" : ((int)s.Arrive.Value.TotalSeconds).ToString()) + ">" + (s.Left == null ? "" : ((int)s.Left.Value.TotalSeconds).ToString())).JoinAsString("|"); return data.ToLower().MD5(); } [OnDeserialized] void Init(StreamingContext ctx) { TrainStopMap = TrainStops == null ? null : TrainStops.Where(s => !string.IsNullOrEmpty(s.Code)).ToDictionary(s => s.Code, StringComparer.OrdinalIgnoreCase); } #region Implementation of IEquatable /// /// 指示当前对象是否等于同一类型的另一个对象。 /// /// /// 如果当前对象等于 参数,则为 true;否则为 false。 /// /// 与此对象进行比较的对象。 public bool Equals(Train other) { return Key == other.Key; } private string _key; public string Key { get { if (string.IsNullOrEmpty(_key)) { _key = Id + Code + From + To; } return _key; } } /// /// 用作特定类型的哈希函数。 /// /// /// 当前 的哈希代码。 /// public override int GetHashCode() { return Key.GetHashCode(); } /// /// 确定指定的 是否等于当前的 。 /// /// /// 如果指定的对象等于当前对象,则为 true;否则为 false。 /// /// 要与当前对象进行比较的对象。 public override bool Equals(object obj) { if (obj == null || !(obj is Train)) return false; return Key == (obj as Train).Key; } #endregion char? _trainClass; /// /// 列车等级 /// [JsonIgnore] public char TrainClass { get { if (_trainClass == null) { if (Code[0] == 'G' || Code[0] == 'D' || Code[0] == 'Z' || Code[0] == 'T') _trainClass = Code[0]; } return _trainClass ?? '*'; } } /// /// 是否是高速列车 /// [JsonIgnore] public bool IsHighSpeedClass { get { var c = TrainClass; return c == 'G' || c == 'D' || c == 'C'; } } } }