Is it possible to skip a C # class object?

I have a C # class that I want to skip as a key / value pair, but don't know how to do it.

Here is what I would like to do:

Foreach (classobjectproperty prop in classobjectname) { if (prop.name == "somename") //do something cool with prop.value } 

Thanks in advance for your help.

+7
c #
source share
2 answers

Yes:

 Type type = typeof(Form); // Or use Type.GetType, etc foreach (PropertyInfo property in type.GetProperties()) { // Do stuff with property } 

This will not give them key / value pairs, but you can get all kinds of information from PropertyInfo .

Please note that this will only give public properties. For non-public, you need to use the overload that takes BindingFlags . If you really only need name / value pairs for the properties of the instance of a particular instance, you can do something like:

 var query = foo.GetType() .GetProperties(BindingFlags.Public | BindingFlags.Instance) // Ignore indexers for simplicity .Where(prop => !prop.GetIndexParameters().Any()) .Select(prop => new { Name = prop.Name, Value = prop.GetValue(foo, null) }); foreach (var pair in query) { Console.WriteLine("{0} = {1}", pair.Name, pair.Value); } 
+12
source share

Check out the solutions here - although this limits accessibility, an approach should work for you to get them all.

0
source share

All Articles