using System.Collections; using System.Collections.Concurrent; namespace Demo.Models; public class MetadataPropertySet : IReadOnlyDictionary { private readonly IDictionary _properties; public MetadataPropertySet() { _properties = new Dictionary(); } public bool ContainsKey(string key) { return _properties.ContainsKey(key); } public bool TryGetValue(string key, out MetadataProperty value) { return _properties.TryGetValue(key, out value); } public IEnumerable Keys => _properties.Keys; public IEnumerable Values => _properties.Values; public MetadataProperty? this[string name] { get => GetValue(name); } internal void SetValue(string name, object value) { if (_properties.TryGetValue(name, out var property)) { property.Value = value; } else { property = new MetadataProperty(name, value); _properties.TryAdd(name, property); } } internal MetadataProperty? GetValue(string name) { if (_properties.TryGetValue(name, out var property)) { return property; } return null; } public class MetadataProperty { public bool IsNull { get; private set; } public Type? Type { get; private set; } private object? _value; /// /// 属性值 /// public object? Value { get => _value; set { IsNull = value is null; Type = value?.GetType(); _value = value; } } public string Name { get; init; } public TValue? Cast() { if (typeof(TValue) == Type) { return (TValue)Convert.ChangeType(Value, Type); } return (TValue)Value; } public MetadataProperty(string name, object? value) { (Name, Value) = (name, value); } public override string ToString() { return Value?.ToString()!; } } public IEnumerator> GetEnumerator() { return _properties.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count => _properties.Count; }