如何显示结构的字段?

Fre*_*ind 4 c# debugging struct

我创建了一个结构:

public struct User {
   public string name;
   public string email;
   public string age;
}
Run Code Online (Sandbox Code Playgroud)

然后创建一个:

 User user = new User();
 user.name = "Freewind";
 user.email = "abc@test.com";
 user.age = 100;
Run Code Online (Sandbox Code Playgroud)

然后显示它:

MessageBox.Show(user.ToString());
Run Code Online (Sandbox Code Playgroud)

我希望它可以打印用户结构的所有字段,但事实并非如此.它只是显示:

MyApp.User
Run Code Online (Sandbox Code Playgroud)

有没有简单的方法来显示结构的所有字段?

Som*_*ved 10

覆盖ToString结构上的方法:

public override string ToString()
{
    return String.Format("name={0}, email={1}, age={2}", this.name, this.email, this.age);
}
Run Code Online (Sandbox Code Playgroud)

请注意,这不是自动的,您必须手动将任何字段/属性添加到字符串.

通过反射,您可以执行以下操作:

public override string ToString()
{
    Type type = this.GetType();
    FieldInfo[] fields = type.GetFields();
    PropertyInfo[] properties = type.GetProperties();
    User user = this;

    Dictionary<string, object> values = new Dictionary<string, object>();
    Array.ForEach(fields, (field) => values.Add(field.Name, field.GetValue(user)));
    Array.ForEach(properties, (property) =>
        {
            if (property.CanRead)
                values.Add(property.Name, property.GetValue(user, null));
        });

    return String.Join(", ", values);
}
Run Code Online (Sandbox Code Playgroud)