假设我有很多对象,它们有很多字符串属性。
是否有编程方式通过它们并输出属性名及其值或是否必须进行硬编码?
是否可能有LINQ方法来查询对象的'string'类型的属性并输出它们?
您是否需要对要回显的属性名称进行硬编码?
答案 0 :(得分:75)
使用反射。它远没有硬编码属性访问那么快,但它可以满足您的需求。
以下查询为对象'myObject'中的每个字符串类型属性生成一个具有Name和Value属性的匿名类型:
var stringPropertyNamesAndValues = myObject.GetType()
.GetProperties()
.Where(pi => pi.PropertyType == typeof(string) && pi.GetGetMethod() != null)
.Select(pi => new
{
Name = pi.Name,
Value = pi.GetGetMethod().Invoke(myObject, null)
});
用法:
foreach (var pair in stringPropertyNamesAndValues)
{
Console.WriteLine("Name: {0}", pair.Name);
Console.WriteLine("Value: {0}", pair.Value);
}
答案 1 :(得分:13)
您可以使用GetProperties
方法获取某个类型的所有属性。然后,您可以使用LINQ Where
扩展方法过滤此列表。最后,您可以使用LINQ Select
扩展方法或方便的快捷方式(如ToDictionary
)来投影属性。
如果要将枚举限制为类型为String
的属性,可以使用以下代码:
IDictionary<String, String> dictionary = myObject.GetType()
.GetProperties()
.Where(p => p.CanRead && p.PropertyType == typeof(String))
.ToDictionary(p => p.Name, p => (String) p.GetValue(myObject, null));
这将创建一个将属性名称映射到属性值的字典。由于属性类型仅限于String
,因此可以将属性值强制转换为String
,并且返回类型的类型为IDictionary<String, String>
。
如果您想要所有属性,可以这样做:
IDictionary<String, Object> dictionary = myObject.GetType()
.GetProperties()
.Where(p => p.CanRead)
.ToDictionary(p => p.Name, p => p.GetValue(myObject, null));
答案 2 :(得分:3)
您可以使用反射来执行此操作....有一篇不错的文章 CodeGuru,但这可能比你正在寻找的更多......你可以从中学习,然后根据你的需要进行修剪。
答案 3 :(得分:3)
如果您的目标只是使用人类可读的格式输出存储在对象属性中的数据,我更喜欢将对象序列化为JSON格式。
using System.Web.Script.Serialization;
//...
string output = new JavaScriptSerializer().Serialize(myObject);
答案 4 :(得分:-2)
这样的事情怎么样?
public string Prop1
{
get { return dic["Prop1"]; }
set { dic["Prop1"] = value; }
}
public string Prop2
{
get { return dic["Prop2"]; }
set { dic["Prop2"] = value; }
}
private Dictionary<string, string> dic = new Dictionary<string, string>();
public IEnumerable<KeyValuePair<string, string>> AllProps
{
get { return dic.GetEnumerator(); }
}