我有对象数组,如何将其包含到控制台?
我需要打印属性及其值。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from terminaltables import AsciiTable
table_data=[
['','a','b','c','d','e','f','g','h','i','j'],
['10','','','','♥','','','♥','','',''],
['9','','','','','','','','','',''],
['8','','','','','','','','','',''],
['7','♥','','','','','','','','','♥'],
['6','','','','','','','','','',''],
['5','','','','','','','','','',''],
['4','♠','','','','','','','','','♠'],
['3','','','','','','','','','',''],
['2','','','','','','','','','',''],
['1','','','♠','','','♠','','','',''],
]
table = AsciiTable(table_data)
table.inner_row_border = True
print table.table
我必须使用反射,但我不知道如何使用它。
答案 0 :(得分:0)
您可以尝试:Console.WriteLine( string.Join(",", attrs) );
答案 1 :(得分:0)
你需要使用反射。这是一个样本:
static void Main(string[] args)
{
string obj1 = "a string";
int obj2 = 12;
DateTime obj3 = DateTime.Today;
object[] obj_array = { obj1, obj2, obj3 };
foreach (object obj in obj_array)
{
//Print value
Console.WriteLine("Value: " + obj.ToString());
//Print property names
Console.WriteLine("Property Names:");
foreach (PropertyInfo prop in obj.GetType().GetProperties())
{
Console.WriteLine(prop.Name);
}
Console.WriteLine();
}
Console.Read();
}
编辑:抱歉,您可能想要检索对象本身的属性值。在这种情况下,这是另一个样本:
class Program
{
static void Main(string[] args)
{
MyObject myobj = new MyObject("prop1", "prop2");
object[] obj_array = { myobj };
foreach (object obj in obj_array)
{
foreach (PropertyInfo property in obj.GetType().GetProperties())
{
Console.WriteLine("Property Name: " + property.Name);
Console.WriteLine("Property Value: " + property.GetValue(obj));
}
}
Console.Read();
}
}
public class MyObject
{
public string Property1 { get; set; }
public string Property2 { get; set; }
public MyObject(string p1, string p2)
{
Property1 = p1;
Property2 = p2;
}
}