C#如何输出一个类中的所有项目(结构)

Ben*_* Ae 2 c# struct class output

我上课基本上只是一排桌子。该行包含许多列。

出于测试目的,我需要输出我得到的读数。

所以我需要输出行中的所有列。

班级就像

    public class tableRow
    {
        public tableRow()
        {}
    public string id
    public string name
    public string reg
    public string data1
    ....
    ....
    ....
   <lot more columns>

}  
Run Code Online (Sandbox Code Playgroud)

然后我需要这样写:

Console.WriteLine("id: " + tableRow.id);
Console.WriteLine("name: " + tableRow.name);
Console.WriteLine("reg: " + tableRow.reg);
Console.WriteLine("data1: " + tableRow.data1);
...
...
...
<lot more Console.WriteLine>
Run Code Online (Sandbox Code Playgroud)

所以我想知道,有没有一种简单的方法来获得所有这些输出,而没有这么多的 console.writeLine?

谢谢

Ser*_*kiy 6

您可以将 tableRow 序列化为 JSON,并且将打印所有列。例如使用JSON.NET(可从 NuGet 获得):

tableRow tr = new tableRow { id = "42", name = "Bob", reg = "Foo" };
Console.WriteLine(JsonConvert.SerializeObject(tr, Formatting.Indented));
Run Code Online (Sandbox Code Playgroud)

输出:

{
  "id": "42",
  "name": "Bob",
  "reg": "Foo",
  "data1": null
}
Run Code Online (Sandbox Code Playgroud)

我使用这种方法进行日志记录(以显示对象状态)- 扩展很好

public static string ToJson<T>(this T obj)
{ 
    return JsonConvert.SerializeObject(tr, Formatting.Indented);
}
Run Code Online (Sandbox Code Playgroud)

用法很简单:

Console.WriteLine(tr.ToJson());
Run Code Online (Sandbox Code Playgroud)


Jer*_*vel 2

这是一个使用反射的简短示例:

void Main()
{
    var myObj = new SomeClass();
    PrintProperties(myObj);

    myObj.test = "haha";
    PrintProperties(myObj);
}

private void PrintProperties(SomeClass myObj){
    foreach(var prop in myObj.GetType().GetProperties()){
     Console.WriteLine (prop.Name + ": " + prop.GetValue(myObj, null));
    }

    foreach(var field in myObj.GetType().GetFields()){
     Console.WriteLine (field.Name + ": " + field.GetValue(myObj));
    }
}

public class SomeClass {
 public string test {get; set; }
 public string test2 {get; set; }
 public int test3 {get;set;}
 public int test4;
}
Run Code Online (Sandbox Code Playgroud)

输出:

test: 
test2: 
test3: 0
test4: 0

test: haha
test2: 
test3: 0
test4: 0
Run Code Online (Sandbox Code Playgroud)