字典的数据类公共属性
本文关键字:属性 数据 字典 | 更新日期: 2023-09-27 18:15:59
我使用以下代码将类的公共属性转换为Dictionary:
public static Dictionary<string, object> ClassPropsToDictionary<T>(T classProps)
{
return classProps.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
.ToDictionary(prop => prop.Name, prop => prop.GetValue(classProps, null));
}
这很好,但我不想要类的引用成员:
public class Unit
{
public virtual string Description { get; set; } // OK
public virtual Employee EmployeeRef { get; set; } // DONT WANT THIS
}
我需要哪个绑定标志来避免EmployeeRef成员?
谢谢
使用Where
与IsClass
属性:
classProps
.GetType()
.GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(x => !x.PropertyType.IsClass)
.ToDictionary(prop => prop.Name, prop => prop.GetValue(classProps, null));
没有BindingFlag
。BindingFlags
大部分与访问修饰符和继承层次结构等有关。不能指定它们来消除值类型或引用类型。如果你不想消除像string
这样的内置类型,那么声明一个数组,将所有类型放入其中,然后使用Contains
:
var allowedTypes = new [] { typeof(string), ... };
.Where(x => !x.PropertyType.IsClass || allowedTypes.Contains(x.PropertyType))
由于大多数内置类型都存在于System
命名空间中,因此也可以简化如下:
.Where(x => !x.PropertyType.IsClass ||
x.PropertyType.AssemblyQualifiedName.StartsWith("System"))
public static Dictionary<string, object> ClassPropsToDictionary<T>(T classProps)
{
return classProps.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(pi => !pi.PropertyType.IsClass || pi.PropertyType == typeof(string))
.ToDictionary(prop => prop.Name, prop => prop.GetValue(classProps, null));
}
要包含结构体吗?你也可以查看IsPrimitive标志,尽管String也是一个对象所以你必须单独包含
classProps.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public).Where(x => x.PropertyType.IsPrimitive || x.PropertyType == typeof(string));