如何向控制台显示作为数组元素的结构的所有字段? C#

How to show all fields of a struct that is an element of an array to the console ? C#

假设我有一个自定义类型的数组,我在其中放入了 10 个自定义结构类型的对象。 CustomType[] Record = new CustomType[10];

现在由于每个 CustomType 都有字段,我可以为数组中的每个 CustomType 元素分配字段。 例如:

Record[0].name = "John";
Record[0].age = 34;

还有 ToString() 方法,它在 int 或 string 等常用类型中,将类型的值转换为 string。所以如果我们有

someIntArray[0] = 32;
Console.WriteLine(someIntArray[0].ToString());

然后我们会在控制台上得到输出“32”,而不是它的值类型,int。

但是如果我们在上面的例子中使用与 CustomType 数组相同的方法,并写成:

Console.WriteLine(Record[0].ToString());

然后我们将不会获得对象包含的值(在其字段中),而是它的类型。 当然我可以这样写:

Console.WriteLine(Record[0].name + Record[0].age);

但是你可以看到,如果结构有很多字段,那么它会很快变得陈旧乏味。特别是如果您不想只打印一个结构对象的所有字段,而是数组中的所有结构对象。

所以这是我的问题:.NET 中是否有方法或其他一些简单的方法可以让我以更简单、更快的方式操作(例如打印)数组元素的所有字段,如结构?

我认为人们假设结构不能包含方法,但它们绝对可以!只需创建一个 ToString() 方法。

您仍然可以在结构中覆盖 ToString()!

struct Record
{
    string name;
    int age;

    public override string ToString()
    {
        return String.Format("{0} {1}", record.name, record.age);
    }

}

因此您不必明确调用它:

Console.WriteLine(record); // e.g., Joe 5