C# 实体属性获取排序字典代码

public class TFSSortDictionary : SortedDictionary<string, object>
{
public TFSSortDictionary() { }

public TFSSortDictionary(IDictionary<string, object> dictionary)
: base(dictionary)
{ }

public void Add(string key, object value)
{
if (!value.IsNullOrEmpty())
{
base.Add(key, value);
}
}

public static IDictionary<string, object> GetDictonary<T>(T data, TFSApiOptions options)
{
try
{
var parameters = new TFSSortDictionary();
var temp = data.GetType();
foreach (PropertyInfo pro in temp.GetProperties())
{
var customAttr = pro.CustomAttributes.FirstOrDefault(w => w.AttributeType == typeof(JsonPropertyAttribute));
if(customAttr!=null)
{
var name = customAttr.NamedArguments.FirstOrDefault().TypedValue.Value.ToString();
var value = pro.GetValue(data);
if (name.ToLower() == nameof(TFSApiOptions.PlatNo).ToLower())
{
if(value.IsNullOrEmpty())
{
value = options.PlatNo;
}
}
parameters.Add(name, value);
}
}
return parameters;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}

public static IDictionary<string, object> GetNoSiginDictonary<T>(T data)
{
try
{
var parameters = new TFSSortDictionary();
var temp = data.GetType();
foreach (PropertyInfo pro in temp.GetProperties())
{
var customAttr = pro.CustomAttributes.FirstOrDefault(w => w.AttributeType == typeof(JsonPropertyAttribute));
if (customAttr != null)
{
var value = customAttr.NamedArguments.FirstOrDefault().TypedValue.Value.ToString();
//过滤字段
if(value == "signature")
{
continue;
}
parameters.Add(value, pro.GetValue(data));
}
}
return parameters;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}

posted @ 2021-02-24 10:11  元点  阅读(227)  评论(0编辑  收藏  举报