您可以使用 Reflection 执行此操作:(从我的库中 - 获取名称和值)
public static Dictionary DictionaryFromType(object atype)
{
if (atype == null) return new Dictionary();
Type t = atype.GetType();
PropertyInfo[] props = t.GetProperties();
Dictionary dict = new Dictionary();
foreach (PropertyInfo prp in props)
{
object value = prp.GetValue(atype, new object[]{});
dict.Add(prp.Name, value);
}
return dict;
}
这个东西不适用于带索引的属性 - 为此(它变得笨拙):
public static Dictionary DictionaryFromType(object atype,
Dictionary indexers)
{
/* replace GetValue() call above with: */
object value = prp.GetValue(atype, ((indexers.ContainsKey(prp.Name)?indexers[prp.Name]:new string[]{});
}
/* replace */
PropertyInfo[] props = t.GetProperties();
/* with */
PropertyInfo[] props = t.GetProperties(BindingFlags.Public)
这也适用于匿名类型!
要获得名称:
public static string[] PropertiesFromType(object atype)
{
if (atype == null) return new string[] {};
Type t = atype.GetType();
PropertyInfo[] props = t.GetProperties();
List propNames = new List();
foreach (PropertyInfo prp in props)
{
propNames.Add(prp.Name);
}
return propNames.ToArray();
}
它只是值,或者你可以使用:
GetDictionaryFromType().Keys
// or
GetDictionaryFromType().Values
但我觉得这有点慢 .