如何获取此类的所有属性
public class Data
{
public Person;
public List<Nationality> nationality;
public List<Passport> passport;
public List<Family> family;
public List<WK_Permit> Permit;
public List<Role> role;
}
预期输出例如是
我想得到类似的东西&#34; DATA.PERSON.NAME&#34;或&#34; DATA.PASSPORT.NUMBER&#34;或者&#34; DATA.ROLES.HOST&#34; ...等所以我必须得到类名和attibuts名称
我这样做但是它不适用于课程列表
Type parent = typeof(VSM_Data);
FieldInfo[] children = parent.GetFields();
for (int i = 0; i < children.Length; i++)
{
Type child = children[i].FieldType;
var columnnamesChild = from t in child.GetProperties() select t.Name;
foreach (var item in columnnamesChild)
{
DragAndDrop FundDragAndDrop = new DragAndDrop();
FundDragAndDrop.TITLE = item;
FundDragAndDrop.adresse = "{{PERSON." + children[i].Name.ToUpper() + "." + item.ToUpper() + "}}";
FundList.Add(FundDragAndDrop);
}
答案 0 :(得分:1)
你可以使用Reflection:
来完成反射;例如:
obj.GetType().GetProperties();
obj.GetType().GetMembers();
表示类型:
typeof(Foo).GetProperties();
typeof(Foo).GetMembers();
例如:
class Foo {
public int A {get;set;}
public string B {get;set;}
public string Member1;
public int Member2;
}
...
对于Fields:
foreach(var prop in foo.GetType().GetFields()) {
Console.WriteLine("{0}={1}", prop.Name);
}
对于属性:
Foo foo = new Foo {A = 1, B = "abc"};
foreach(var prop in foo.GetType().GetProperties()) {
Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));
}
对于会员:
foreach(var prop in foo.GetType().GetMembers()) {
Console.WriteLine("{0}", prop.Name);
}
答案 1 :(得分:0)
static void Main(string[] args)
{
Data data = new Data();
//you can use this for your case
var fields = data.GetType().GetFields().Select(f => f.Name);
foreach (var f in fields)
{
Console.WriteLine(f);
}
Console.WriteLine("===");
//but if you want a more generic one try this
var members = data.GetType().GetMembers().Select(m=>m.Name);
foreach (var member in members)
{
Console.WriteLine(member);
}
}
答案 2 :(得分:0)
此代码将为您提供所有公共属性名称
Type type = typeof(Data);
foreach (var property in type.GetProperties())
string name = property.Name;
答案 3 :(得分:0)
我可以找到解决方案,有时找到解决方案的最佳方法是提出问题并自己思考; - )
Type type = typeof(VSM_Data);
foreach (var property in type.GetFields())
{
FieldInfo[] children = type.GetFields();
for (int i = 0; i < children.Length; i++)
{
Type child = property.FieldType;
var columnnamesChild = from t in child.GetFields() select t.Name;
foreach (var item in columnnamesChild)
{
DragAndDrop FundDragAndDrop = new DragAndDrop();
FundDragAndDrop.TITLE = item;
FundDragAndDrop.adresse = "{{PERSON." + children[i].Name.ToUpper() + "." + item.ToUpper() + "}}";
FundList.Add(FundDragAndDrop);
}
}
}