![](/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.