using Apewer.Internals;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace Apewer
{
/// 标题特性。
[Serializable]
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
public class CaptionAttribute : Attribute
{
private string _title, _description, _remark;
///
public CaptionAttribute(string title = null, string description = null, string remark = null)
{
Title = title;
Description = description;
Remark = remark;
}
///
public string Title
{
get { return _title; }
set { _title = value ?? Constant.EmptyString; }
}
///
public string Description
{
get { return _description; }
set { _description = value ?? Constant.EmptyString; }
}
///
public string Remark
{
get { return _remark; }
set { _remark = value ?? Constant.EmptyString; }
}
/// 从 到 Boolean 的隐式转换,判断 有效。
public static implicit operator bool(CaptionAttribute instance) => instance != null;
#region static
static Dictionary _cache = new Dictionary();
/// 解析标题特性,默认使用缓存以提升性能。
/// 若修改已缓存实例的属性值,则下次从缓存中获取实例时将带有新的属性值。
/// 已存在的 实例。
public static CaptionAttribute Parse(Type type, bool useCache = true)
{
if (type == null) return null;
var cacheKey = type.FullName;
if (useCache)
{
var hint = null as CaptionAttribute;
lock (_cache)
{
if (_cache.ContainsKey(cacheKey))
{
hint = _cache[cacheKey];
}
}
if (hint != null) return hint;
}
var attributes = type.GetCustomAttributes(typeof(CaptionAttribute), false);
if (attributes.LongLength < 1L) return null;
var attribute = (CaptionAttribute)attributes[0];
if (useCache)
{
lock (_cache)
{
if (!_cache.ContainsKey(cacheKey)) _cache.Add(cacheKey, attribute);
}
}
return attribute;
}
/// 解析标题特性,默认使用缓存以提升性能。
/// 若修改已缓存实例的属性值,则下次从缓存中获取实例时将带有新的属性值。
/// 已存在的 实例。
public static CaptionAttribute Parse(bool useCache = true) => Parse(typeof(T), useCache);
#endregion
}
}