using System; using System.Linq; using System.Collections; using System.Collections.Generic; using Microsoft.SqlServer.Server; using System.IO; namespace BITKit { /// /// 属性接口,用于序列化引用 /// public interface IProperty { } /// /// 属性接口 /// GetOrCreate(√) /// GetOrAdd(√) /// TryGet(√) /// TryRemove(√) /// TrySet(√) /// GetProperties(√) /// public interface IPropertable: IBinarySerialize { /// /// 是否拥有属性 /// bool Contains(); /// /// 获取或创建属性 /// T GetOrCreateProperty(); /// /// 获取或通过工厂方法添加属性 /// T GetOrAddProperty(Func addFactory); /// /// 尝试获取属性 /// bool TryGetProperty(out T value); /// /// 尝试移除属性 /// bool TryRemoveProperty(); /// /// 尝试设置属性 /// bool TrySetProperty(T value); /// /// 获取所有属性 /// object[] GetProperties(); /// /// 清除所有属性 /// /// bool ClearProperties(); /// /// 从其他对象复制属性 /// /// /// bool CopyPropertiesFrom(IPropertable propertable); } public class Property : IPropertable { public Property() { } public Property(IEnumerable factory) { foreach (var x in factory) { properties.Add(x.GetType().FullName, x); } } Dictionary properties=new(); public T GetProperty() { return (T)properties[typeof(T).FullName]; } public void SetProperty(T value) { properties.Insert(typeof(T).FullName, value); } public bool Contains() { return properties.ContainsKey(typeof(T).FullName); } public T GetOrCreateProperty() { return GetOrAddProperty(Activator.CreateInstance); } public T GetOrAddProperty(Func addFactory) { if (properties.TryGetValue(typeof(T).FullName, out var x)) { return (T)x; } else { properties.Add(typeof(T).FullName, x = addFactory.Invoke()); return (T)x; } } public bool TryGetProperty(out T value) { if (properties.TryGetValue(typeof(T).FullName, out var x)) { value = (T)x; return true; } else { value=default(T); return false; } } public bool TryRemoveProperty() { if(properties.TryGetValue(typeof(T).FullName, out var x)) { properties.Remove(typeof(T).Name); return true; } return false; } public bool TrySetProperty(T value) { if (properties.TryGetValue(typeof(T).FullName, out var x)) { properties[typeof(T).FullName] = value; return true; } else { return false; } } public object[] GetProperties()=>properties.Values.ToArray(); public void Read(BinaryReader r) { foreach (var x in properties) { } } public void Write(BinaryWriter w) { throw new NotImplementedException(); } public bool ClearProperties() { properties.Clear(); return true; } public bool CopyPropertiesFrom(IPropertable propertable) { ClearProperties(); foreach (var x in propertable.GetProperties()) { properties.Add(x.GetType().FullName, x); } return true; } } }