是否可以遍历C#Class对象?

SLo*_*ret 8 c#

我有一个C#类,我想循环通过属性作为键/值对但不知道如何.

这是我想做的事情:

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

Jon*_*eet 13

对:

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

这不会给它们作为键/值对,但是你可以从a获得各种信息PropertyInfo.

请注意,这只会提供公共属性.对于非公开的,你想要使用带有a的重载BindingFlags.如果您真的只想要名称/值对作为特定实例的实例属性,您可以执行以下操作:

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);
}
Run Code Online (Sandbox Code Playgroud)