【问题标题】:C# how to output all the items in a class(struct) [duplicate]C#如何输出类(结构)中的所有项目[重复]
【发布时间】:2013-11-18 09:03:30
【问题描述】:

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

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

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

类是这样的

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

}  

那么我需要这样写:

Console.WriteLine("id: " + tableRow.id);
Console.WriteLine("name: " + tableRow.name);
Console.WriteLine("reg: " + tableRow.reg);
Console.WriteLine("data1: " + tableRow.data1);
...
...
...
<lot more Console.WriteLine>

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

谢谢

【问题讨论】:

  • 阅读反思,这是最简单的工作工具。
  • 你可以通过反射来做到这一点。如果您搜索它们,您可以找到示例。

标签: c# class struct output


【解决方案1】:

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

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

输出:

{
  "id": "42",
  "name": "Bob",
  "reg": "Foo",
  "data1": null
}

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

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

用法很简单:

Console.WriteLine(tr.ToJson());

【讨论】:

    【解决方案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;
    }
    

    输出:

    test: 
    test2: 
    test3: 0
    test4: 0
    
    test: haha
    test2: 
    test3: 0
    test4: 0
    

    【讨论】:

      【解决方案3】:

      这应该适用于类以及具有自定义类型描述符的类型:

      private static void Dump(object o)
      {
          if (o == null)
          {
              Console.WriteLine("<null>");
              return;
          }
      
          var type = o.GetType();
          var properties = TypeDescriptor.GetProperties(type);
      
          Console.Write('{');
          Console.Write(type.Name);
      
          if (properties.Count != 0)
          {
              Console.Write(' ');
      
              for (int i = 0, n = properties.Count; i < n; i++)
              {
                  if (i != 0)
                      Console.Write("; ");
      
                  var property = properties[i];
      
                  Console.Write(property.Name);
                  Console.Write(" = ");
                  Console.Write(property.GetValue(o));
              }
          }
      
          Console.WriteLine('}');
      }
      

      如果要转储字段而不是属性,可以使用type.GetFields() 并对上述代码进行必要的修改。 FieldInfo 有一个类似的GetValue() 方法。

      请注意,这不会打印记录的“深度”表示。为此,您可以将其调整为递归解决方案。您可能还希望支持集合/数组、引用字符串和识别循环引用。

      【讨论】:

      • 这仅适用于属性,OP 有字段。一个简单的修复(你有很好的反射基础),只是需要注意
      • 它们不是正确的字段声明,所以我认为他只是在速记中输入。但是,是的,你是对的。
      【解决方案4】:

      你可以使用反射来做到这一点...给我一分钟,我会发布一些代码

      一些东西:

      PropertyInfo[] propertyInfos;
      propertyInfos = typeof(MyClass).GetProperties(BindingFlags.Public |
                                                    BindingFlags.Static);
      // sort properties by name
      Array.Sort(propertyInfos,
              delegate(PropertyInfo propertyInfo1, PropertyInfo propertyInfo2)
              { return propertyInfo1.Name.CompareTo(propertyInfo2.Name); });
      
      // write property names
      foreach (PropertyInfo propertyInfo in propertyInfos)
      {
        Console.WriteLine(propertyInfo.Name);
      }
      

      您可以添加一个检查以查看它是一个字符串,并添加一些输出,但这就是它的 git。

      来源here

      【讨论】:

      • 如果您还没有问题的答案,那么您不应该发布答案。当您对问题有实际答案时然后发布答案。发布非答案只是为了获得更早的时间戳是不合适的行为。
      【解决方案5】:

      如果你设置了一个字符串数组

      var dataFields = new string[] { "id", "name", ...
      

      您可以执行一个 foreach 循环来填充表格,并使用相同的数组引用表格数据,从而允许您执行另一个 foreach 循环来执行 Console.WriteLine 调用

      如果您愿意,每个表行可以只是一个字典,其中数据字段作为键,数据作为值。然后你就可以遍历字典了

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-07-27
        • 1970-01-01
        • 1970-01-01
        • 2010-10-07
        • 1970-01-01
        • 2011-06-15
        • 2018-07-30
        • 1970-01-01
        相关资源
        最近更新 更多