且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-09 14:48:55

使用反射.它的速度远不及硬编码的属性访问,但它可以满足您的需求.

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

以下查询为对象myObject"中的每个字符串类型属性生成一个具有 Name 和 Value 属性的匿名类型:

The following query generates an anonymous type with Name and Value properties for each string-typed property in the object '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);
}