标签:returns this 记录 ryu info object reac bre 实体类
public static class TypeExtensions
{
public static bool InheritsFrom(this Type source, Type target)
{
if (null == source || null == target)
{
return false;
}
if (source == target)
{
return true;
}
if (source.GetTypeInfo().IsGenericType && source.GetTypeInfo().GetGenericTypeDefinition() == target)
{
return true;
}
if (source.GetTypeInfo().GetInterfaces().Any(i => i.GetTypeInfo().IsGenericType && i.GetGenericTypeDefinition() == target || i == target))
{
return true;
}
return source.GetTypeInfo().BaseType != null &&
InheritsFrom(source.GetTypeInfo().BaseType, target);
}
}
public class ModelHistoryUtils
{
/// <summary>
/// 获取实体变更记录
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public static string GetRecord(object model)
{
if (null == model)
{
return string.Empty;
}
Type type = model.GetType();
StringBuilder sbResult = new StringBuilder("<ul>");
try
{
if (typeof(string) == type || type.IsPrimitive)
{
sbResult.Append(model.ToString());
}
else if (type.InheritsFrom(typeof(Dictionary<,>)))
{
StringBuilder sbDic = new StringBuilder("<ul>");
IDictionary dictionary = ((IDictionary)model);
foreach (var key in dictionary.Keys)
{
sbDic.Append($"<li><b>{GetRecord(key, false)}:</b>{GetRecord(dictionary[key], false)}</li>");
}
sbResult.Append("</ul>");
}
else if (type.InheritsFrom(typeof(IEnumerable)))
{
List<string> lstRecord = ((IEnumerable)model)
.Cast<object>()
.Select(item => $"<li>{GetRecord(item, false)}</li>")
.ToList() ?? new List<string>();
sbResult.Append($"<ul>{string.Join("", lstRecord)}</ul>");
}
else
{
PropertyInfo[] lstProperty = type.GetProperties();
DescriptionAttribute description;
foreach (PropertyInfo prop in lstProperty)
{
description = prop.GetCustomAttribute<DescriptionAttribute>();
if (null != description)
{
string value = "";
if (prop.PropertyType.InheritsFrom(typeof(IEnumerable)) && typeof(string) != prop.PropertyType)
{
value = GetRecord(prop.GetValue(model), false);
}
else
{
value = prop.GetValue(model)?.ToString() ?? "";
}
sbResult.Append($"<li><b>{description.Description}:</b>{value}</li>");
}
}
}
}
catch (Exception ex)
{
}
sbResult.Append("</ul>");
return sbResult.ToString();
}
}
标签:returns this 记录 ryu info object reac bre 实体类
原文地址:https://www.cnblogs.com/AlvinLee/p/10192011.html