110 lines
2.5 KiB
C#
110 lines
2.5 KiB
C#
|
using System.Collections;
|
||
|
using System.Collections.Concurrent;
|
||
|
|
||
|
namespace Demo.Models;
|
||
|
|
||
|
public class MetadataPropertySet : IReadOnlyDictionary<string, MetadataPropertySet.MetadataProperty>
|
||
|
{
|
||
|
private readonly IDictionary<string, MetadataProperty> _properties;
|
||
|
|
||
|
public MetadataPropertySet()
|
||
|
{
|
||
|
_properties = new Dictionary<string, MetadataProperty>();
|
||
|
}
|
||
|
|
||
|
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<string> Keys => _properties.Keys;
|
||
|
public IEnumerable<MetadataProperty> 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;
|
||
|
/// <summary>
|
||
|
/// 属性值
|
||
|
/// </summary>
|
||
|
public object? Value
|
||
|
{
|
||
|
get => _value;
|
||
|
set
|
||
|
{
|
||
|
IsNull = value is null;
|
||
|
Type = value?.GetType();
|
||
|
_value = value;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
public string Name { get; init; }
|
||
|
|
||
|
public TValue? Cast<TValue>()
|
||
|
{
|
||
|
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<KeyValuePair<string, MetadataProperty>> GetEnumerator()
|
||
|
{
|
||
|
return _properties.GetEnumerator();
|
||
|
}
|
||
|
|
||
|
IEnumerator IEnumerable.GetEnumerator()
|
||
|
{
|
||
|
return GetEnumerator();
|
||
|
}
|
||
|
|
||
|
public int Count => _properties.Count;
|
||
|
}
|