C# 动态类转换(将对象转成字典)
public class DynamicClassTransformation
{
private readonly Dictionary<string, dynamic> Keys;
public DynamicClassTransformation(object obj)
{
var properties = obj.GetType().GetProperties();
Keys = new Dictionary<string, dynamic>();
foreach (System.Reflection.PropertyInfo info in properties)
{
var value = info.GetValue(obj, null);
Keys.Add(info.Name,value );
}
}
public Dictionary<string, dynamic> GetValue()
{
return Keys;
}
public AddResult<bool> Add(string key, dynamic value)
{
try {
Keys.Add(key, value);
return new AddResult<bool>(true);
} catch {
return new AddResult<bool>("属性已存在,添加失败");
}
}
public bool Remove(string key)
{
return Keys.Remove(key);
}
}
public static partial class Extention
{
public static DynamicClassTransformation ToDictionary(this object obj)
{
return new DynamicClassTransformation(obj);
}
}