c# - Get fields from any class (based on type) -


i have class class1

public class class1 {     public string abc { get; set; }     public string def { get; set; }     public string ghi { get; set; }     public string jlk { get; set; } } 

how can list of, in case 'abc', 'def', ... want name of public fields.

i tried following:

dictionary<string, string> props = new dictionary<string, string>();  foreach (var prop in classtype.gettype().getproperties().where(x => x.canwrite == true).tolist()) {     //console.writeline("{0}={1}", prop.name, prop.getvalue(classitem, null));     //objectitem.setvalue("abc", "test");     props.add(prop.name, ""); } 

and:

var bindingflags = bindingflags.instance | bindingflags.nonpublic | bindingflags.public; var fieldvalues = classtype.gettype()                             .getfields(bindingflags)                             .select(field => field.getvalue(classtype))                             .tolist(); 

but neither gave me wanted results.

thanks in advance

try this:

using system; using system.linq;  public class class1 {     public string abc { get; set; }     public string def { get; set; }     public string ghi { get; set; }     public string jlk { get; set; } }  class program {     static void main()     {         // if know type @ compilation time         var propertynames              = typeof(class1).getproperties().select(x => x.name);          // if have instance of type         var instance = new class1();         var propertynamesfrominstance              = instance.gettype().getproperties().select(x => x.name);     } } 

Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -