【发布时间】:2010-11-29 15:47:59
【问题描述】:
假设我有很多对象,它们有很多字符串属性。
是否有一种编程方式来遍历它们并输出属性名称及其值,还是必须硬编码?
是否有一种 LINQ 方法可以查询“字符串”类型的对象的属性并输出它们?
您是否必须对要回显的属性名称进行硬编码?
【问题讨论】:
标签: c# .net linq properties
假设我有很多对象,它们有很多字符串属性。
是否有一种编程方式来遍历它们并输出属性名称及其值,还是必须硬编码?
是否有一种 LINQ 方法可以查询“字符串”类型的对象的属性并输出它们?
您是否必须对要回显的属性名称进行硬编码?
【问题讨论】:
标签: c# .net linq properties
使用反射。它远没有硬编码的属性访问快,但它可以满足您的需求。
以下查询为对象“myObject”中的每个字符串类型属性生成一个具有名称和值属性的匿名类型:
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);
}
【讨论】:
您可以使用反射来执行此操作...。有一篇不错的文章 CodeGuru,但这可能比您想要的要多...您可以从中学习,然后根据您的需要进行调整。
【讨论】:
这样的事情怎么样?
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(); }
}
【讨论】:
您可以使用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));
【讨论】:
如果您的目标只是使用人类可读的格式输出存储在对象属性中的数据,我更喜欢简单地将对象序列化为 JSON 格式。
using System.Web.Script.Serialization;
//...
string output = new JavaScriptSerializer().Serialize(myObject);
【讨论】: