![](/img/trans.png)
[英]Using reflection how can we tell if a class property is a nullable collection and get its data type?
[英]Class property name and its data type for sub class using Reflection
我正在尝试动态获取任何类的类属性名称及其数据类型,以便可以构建Db所需的架构模型,例如Google BigQuery。 我能够获取字符串或int属性的名称和类型,但是使用数组或自定义类的列表不确定如何获取其类的属性和名称。
我的模型是:
public class StateModel
{
public string State { get; set; }
public string Gender { get; set; }
public int Year { get; set; }
public string Name { get; set; }
public int Number { get; set; }
public int[] Items { get; set; }
public List<string> Values { get; set; }
public Coordinate[] OrdinateArray { get; set; }
public List<Coordinate> Ordinates { get; set; }
public Coordinate CoordinateObj { get; set; }
}
public class Coordinate
{
public int Point { get; set; }
public string Value { get; set; }
}
我获得类属性的方法是:
public static Dictionary<string, object> GetColumnFromClass<T>() where T : class, new()
{
Dictionary<string, object> fields = new Dictionary<string, object>();
T obj = new T();
var type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (var item in properties)
{
fields.Add(item.Name, item.PropertyType.Name.ToUpper())
}
return fields;
}
谁能帮我从以下属性中获取坐标类详细信息,即(坐标类的点和值名称):
public Coordinate[] OrdinateArray { get; set; }
public List<Coordinate> Ordinates { get; set; }
public Coordinate CoordinateObj { get; set; }
注意:我需要动态获取子类详细信息,而不是硬编码。
请查看这是否满足您的要求(父项和子项中的相同属性名将导致仅父项的一项,可以使用递归深度参数来处理):
private static ConcurrentDictionary<string, object> GetColumnFromClass(object obj, ConcurrentDictionary<string, object> fields)
{
//null type will not be processed
if (obj == null)
return null;
Type objType = obj.GetType();
PropertyInfo[] properties = objType.GetProperties();
foreach (PropertyInfo property in properties)
{
if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(List<>))
{
Type itemType = property.PropertyType.GetGenericArguments()[0];
if (itemType == typeof(string))
fields.AddOrUpdate(property.Name, property.PropertyType.Name.ToUpper(), (k, o) => o);
else
{
fields.AddOrUpdate(property.Name, property.PropertyType.Name.ToUpper(), (k, o) => o);
GetColumnFromClass(Activator.CreateInstance(itemType), fields);
}
}
else
{
object propVal = property.GetValue(obj, null);
if (property.PropertyType.Assembly == objType.Assembly)
{
fields.AddOrUpdate(property.Name, property.PropertyType.Name.ToUpper(), (k,o) => o);
GetColumnFromClass(propVal, fields);
}
else
{
fields.AddOrUpdate(property.Name, property.PropertyType.Name.ToUpper(), (k, o) => o);
}
}
}
return fields;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.