循环遍历对象中的已知属性

Jam*_*xon 1 c# properties

我有一个包含30个属性的对象,我知道它们的名字.这些属性称为"ValueX"(1-30),其中X是数字.

我如何在循环中调用value1 - value30?

Dav*_*rab 7

用反射.

public static string PrintObjectProperties(this object obj)
{
    try
    {
        System.Text.StringBuilder sb = new StringBuilder();

        Type t = obj.GetType();

        System.Reflection.PropertyInfo[] properties = t.GetProperties();

        sb.AppendFormat("Type: '{0}'", t.Name);

        foreach (var item in properties)
        {
            object objValue = item.GetValue(obj, null);

            sb.AppendFormat("|{0}: '{1}'", item.Name, (objValue == null ? "NULL" : objValue));
        }

        return sb.ToString();
    }
    catch
    {
        return obj.ToString();
    }
}
Run Code Online (Sandbox Code Playgroud)