Thursday, 15 July 2010

c# - Failing to get fields of an object -



c# - Failing to get fields of an object -

simple c# console application check how fields of unknown object.

public class { public int id; public string name; public string desc; } class programme { static void main(string[] args) { a = new a(); getprop(a); console.readkey(); } static object getprop(object o) { type type = o.gettype(); propertyinfo[] pros = type.getproperties(bindingflags.public | bindingflags.nonpublic | bindingflags.instance); //do homecoming null; } }

i not getting fields. pros has no value within it. have field names of object o.

the members you're trying fetch not properties, fields. seek following:

var fields = typeof(a).getfields();

or:

static fieldinfo[] getfields(object o) { type type = o.gettype(); fieldinfo[] fields = type.getfields(); homecoming fields; }

and in order grab object's fields values:

var fields = getfields(obj); foreach(var field in fields) { console.writeline(field.getvalue(obj)); }

from msdn:

type.getfields method

returns public fields of current type.

c#

No comments:

Post a Comment