using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; namespace BITKit { /// /// 属性接口,用于序列化引用 /// public interface IProperty { } /// /// 属性接口 /// GetOrCreate(√) /// GetOrAdd(√) /// TryGet(√) /// TryRemove(√) /// TrySet(√) /// GetProperties(√) /// public interface IPropertable { /// /// 是否拥有属性 /// 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); } } private readonly List properties=new(); public T GetProperty() { return properties.OfType().First(); } public void SetProperty(T value) { for (var i = 0; i < properties.Count; i++) { if (properties[i] is T) properties[i] = value; } } public bool Contains() { return properties.OfType().FirstOrDefault() is not null; } public T GetOrCreateProperty() { return GetOrAddProperty(Activator.CreateInstance); } public T GetOrAddProperty(Func addFactory) { foreach (var obj in properties) { if (obj is T t) return t; } T x; properties.Add(x = addFactory.Invoke()); return x; } public bool TryGetProperty(out T value) { try { value = properties.OfType().First(); return true; } catch (InvalidOperationException) { value = default; return false; } } public bool TryRemoveProperty() { var removed=false; foreach (var value in properties.OfType().ToArray()) { properties.Remove(value); removed = true; } // if(properties.TryGetValue(typeof(T).FullName, out var x)) // { // properties.Remove(typeof(T).Name); // return true; // } return removed; } public bool TrySetProperty(T value) { var current = properties.OfType().FirstOrDefault(); if (current is not null) { properties.Remove(current); return true; } properties.Add(value); return false; } public object[] GetProperties() => properties.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(); properties.AddRange( propertable.GetProperties());; return true; } } }