我有对象数组,我如何打印其包含到控制台?
我需要打印属性和它的值
object[] attrs;
attrs = prop.GetCustomAttributes(true);
我必须使用反射,但我不知道如何使用它。
您需要使用反射。下面是一个示例:
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;
}
}
您可以尝试:Console.WriteLine( string.Join(",", attrs) );