在 C# 中枚举对象的属性(字符串)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1447308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 17:37:19  来源:igfitidea点击:

Enumerating through an object's properties (string) in C#

c#.netlinqproperties

提问by Matt

Let's say I have many objects and they have many string properties.

假设我有很多对象,它们有很多字符串属性。

Is there a programatic way to go through them and output the propertyname and its value or does it have to be hard coded?

是否有一种编程方式来遍历它们并输出属性名称及其值,还是必须对其进行硬编码?

Is there maybe a LINQ way to query an object's properties of type 'string' and to output them?

是否有 LINQ 方法来查询“字符串”类型的对象属性并输出它们?

Do you have to hard code the property names you want to echo?

您是否必须对要回显的属性名称进行硬编码?

采纳答案by Ben M

Use reflection. It's nowhere near as fast as hardcoded property access, but it does what you want.

使用反射。它远不如硬编码的属性访问快,但它可以满足您的需求。

The following query generates an anonymous type with Name and Value properties for each string-typed property in the object 'myObject':

以下查询为对象“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)
    });

Usage:

用法:

foreach (var pair in stringPropertyNamesAndValues)
{
    Console.WriteLine("Name: {0}", pair.Name);
    Console.WriteLine("Value: {0}", pair.Value);
}

回答by Michael Bray

You can use reflection to do this... . there is a decent article at CodeGuru, but that may be more than you are looking for... you can learn from it, and then trim it to your needs.

你可以使用反射来做到这一点...... CodeGuru 上有一篇不错的文章 ,但这可能比您想要的要多……您可以从中学习,然后根据您的需要进行调整。

回答by Axl

How about something like this?

这样的事情怎么样?

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(); }
}

回答by Martin Liversage

You can get all the properties of a type by using the GetPropertiesmethod. You can then filter this list using the LINQ Whereextension method. Finally you can project the properties using the LINQ Selectextension method or a convenient shortcut like ToDictionary.

您可以使用该GetProperties方法获取一个类型的所有属性。然后,您可以使用 LINQWhere扩展方法过滤此列表。最后,您可以使用 LINQSelect扩展方法或方便的快捷方式(如ToDictionary.

If you want to limit the enumeration to properties having of type Stringyou can use this code:

如果要将枚举限制为具有类型的属性,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));

This will create a dictionary that maps property names to property values. As the property type is limited to Stringit is safe to cast the property value to Stringand the type of the returned type is IDictionary<String, String>.

这将创建一个将属性名称映射到属性值的字典。由于属性类型仅限于String将属性值强制转换为安全,String并且返回类型的类型为IDictionary<String, String>.

If you instead want all properties you can do it like this:

如果你想要所有属性,你可以这样做:

IDictionary<String, Object> dictionary = myObject.GetType()
  .GetProperties()
  .Where(p => p.CanRead)
  .ToDictionary(p => p.Name, p => p.GetValue(myObject, null));

回答by Karl Wenzel

If your goal is simply to output the data stored in the object's properties using a human-readable format, I prefer to simply serialize the object into JSON format.

如果您的目标只是使用人类可读的格式输出存储在对象属性中的数据,我更喜欢简单地将对象序列化为 JSON 格式。

using System.Web.Script.Serialization;
//...

string output = new JavaScriptSerializer().Serialize(myObject);