实现方法:
private static readonly ConcurrentDictionary<RuntimeTypeHandle, PropertyInfo[]>
_dynamicObjectProperties = new ConcurrentDictionary<RuntimeTypeHandle, PropertyInfo[]>();
/// <summary>
/// 获取对象属性
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
private static PropertyInfo[] GetObjectProperties<T>()
{
var type = typeof(T);
var key = type.TypeHandle;
PropertyInfo[] queryPts = null;
_dynamicObjectProperties.TryGetValue(key, out queryPts);
if (queryPts == null)
{
queryPts = type.GetProperties();
_dynamicObjectProperties.TryAdd(key, queryPts);
}
return queryPts;
}
使用例子:
public object Transform()
{
var obj = new KeyValue() { Key = "111", Value = "aaa", Value2 = "test" };
var targetPts = GetObjectProperties<KeyValue>();
var dynamicResult = new ExpandoObject() as IDictionary<string, Object>;
foreach (var item in targetPts)
{
//字段是否标记 忽略 属性
var attributes = item.GetCustomAttributes(typeof(IngorePropertyAttribute), true);
if (attributes.FirstOrDefault() != null)
continue;
var name = item.Name;
var value = item.GetValue(obj, null);
if (name.Equals("Key"))continue;
dynamicResult.Add(item.Name, item.GetValue(obj, null));
}
return dynamicResult;
}
public class KeyValue
{
public string Key { get; set; }
public string Value { get; set; }
[IngoreProperty]
public string Value2 { get; set; }
}
/// <summary>
/// 动态输出时忽略此标记的属性
/// </summary>
public class IngorePropertyAttribute : Attribute
{
}
结果返回:
{"Value":"aaa"}