我需要将对象中的所有数据转储为二维数组
这是宣言:
GetItemCall oGetItemCall = new GetItemCall(oContext);
然后,我可以使用oGetItemCall.Item.ConditionID
或oGetItemCall.Item.ListingDetails.EndTime
等
但oGetItemCall
对象有很多变量,我想将它们添加到一个易于阅读的二维数组中。
有没有办法做到这一点?
答案 0 :(得分:0)
需要数组吗? 为什么不使用更灵活的结构,如列表。所以尝试将对象转换为列表。可以通过索引轻松访问list:在这种情况下,通过对象的属性名称。 Reflection可以解决问题。 看看here。
答案 1 :(得分:0)
目前尚不清楚为什么要这样做,但其中任何一个都应该这样做。
string[,] some = new string[100,2];
Hashtable table = new Hashtable();
// array
some[0,0] = "Key";
some[0,1] = "value";
// hashtable
table["key"] = "value";
答案 2 :(得分:0)
所以你想看看这个项目及其所有的属性和价值观?使用反射。
它并不完美,绝不是完整的 - 但如果这是你想要的,它会给你一个很好的起点。可轻松扩展以添加类型名称等。
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