我需要将对象中的所有数据转储到二维数组中
这是声明:
GetItemCall oGetItemCall = new GetItemCall(oContext);
然后,我可以使用oGetItemCall.Item.ConditionID
oroGetItemCall.Item.ListingDetails.EndTime
等。
但是该oGetItemCall
对象有很多变量,我想将它们添加到一个易于阅读的二维数组中。有什么办法吗?
目前尚不清楚您为什么要这样做,但是其中任何一个都应该这样做。
string[,] some = new string[100,2];
Hashtable table = new Hashtable();
// array
some[0,0] = "Key";
some[0,1] = "value";
// hashtable
table["key"] = "value";
因此,您想查看项目及其所有属性和值吗?使用反射。
它并不完美,也不完整——但如果这是你想要的,它会给你一个很好的起点。易于扩展以添加类型名称等。
public static List<string> ReflectObject(object o)
{
var items = new List<string>();
if (o == null)
{
items.Add("NULL"); // remove if you're not interested in NULLs.
return items;
}
Type type = o.GetType();
if (type.IsPrimitive || o is string)
{
items.Add(o.ToString());
return items;
}
items.Add(string.Format("{0}{1}{0}", " ----- ", type.Name));
if (o is IEnumerable)
{
IEnumerable collection = (IEnumerable)o;
var enumerator = collection.GetEnumerator();
while (enumerator.MoveNext())
{
foreach (var innerItem in ReflectObject(enumerator.Current))
{
items.Add(innerItem);
}
}
}
else
{
var properties = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var property in properties)
{
object value = property.GetValue(o, null);
foreach (var innerItem in ReflectObject(value))
{
items.Add(string.Format("{0}: {1}", property.Name, innerItem));
}
}
}
return items;
}
它可以这样使用:
Test t = new Test();
t.MyProperty1 = 123;
t.MyProperty2 = "hello";
t.MyProperty3 = new List<string>() { "one", "two" };
t.MyTestProperty = new Test();
t.MyTestProperty.MyProperty1 = 987;
t.MyTestProperty.MyTestProperty = new Test();
t.MyTestProperty.MyTestProperty.MyProperty2 = "goodbye";
var items = MyReflector.ReflectObject(t);
foreach (var item in items)
{
Console.WriteLine(item);
}
这将导致:
----- Test -----
MyProperty1: 123
MyProperty2: hello
MyProperty3: ----- List`1 -----
MyProperty3: one
MyProperty3: two
MyTestProperty: ----- Test -----
MyTestProperty: MyProperty1: 987
MyTestProperty: MyProperty2: NULL
MyTestProperty: MyProperty3: NULL
MyTestProperty: MyTestProperty: ----- Test -----
MyTestProperty: MyTestProperty: MyProperty1: 0
MyTestProperty: MyTestProperty: MyProperty2: goodbye
MyTestProperty: MyTestProperty: MyProperty3: NULL
MyTestProperty: MyTestProperty: MyTestProperty: NULL