1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- using Newtonsoft.Json;
- using System;
- using System.ComponentModel;
- using System.Linq;
- using System.Runtime.CompilerServices;
- using System.Security.Cryptography;
- using System.Text;
- /// <summary>
- /// 网络同步数据基类 2022.5.27 gwang
- /// </summary>
- public abstract class Base_NetSyncData : INetSyncData, INotifyPropertyChanged
- {
- [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
- protected class JsonRawAttribute : Attribute
- {
- }
- public Base_NetSyncData() => this.PropertyChanged += (s, e) => IsChanged = true;
- [JsonIgnore]
- public virtual bool IsChanged { get; private set; }
- public event PropertyChangedEventHandler? PropertyChanged;
- protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "") =>
- PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
- /// <summary>需要在actor线(协)程内部调用才安全</summary>
- public virtual void ClearChanges() => this.IsChanged = false;
- /// <summary>
- /// 序列化为json串
- /// </summary>
- virtual public string Json() => JsonConvert.SerializeObject(this);
- public override string ToString()
- {
- return this.Json();
- }
- /// <summary>
- /// 计算自身数据(序列化为json串后)的MD5值
- /// </summary>
- /// <param name="tolower">是否转为小写字符串,默认:false</param>
- virtual public string Md5(bool tolower = false)
- {
- var sb = new StringBuilder();
- var md5 = MD5.Create();
- byte[] hash = md5.ComputeHash(Encoding.UTF8.GetBytes(Json())); // 计算MD5的值
- hash.ToList().ForEach(i => sb.Append(tolower ? $"{i:x2}" : $"{i:X2}")); // 转为32位16进制字大写(或者小写)符串
- return sb.ToString();
- }
- }
|