You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从字符串路径获取List指定索引对象的属性值?

实现方法

1. 字符串解析(正则表达式)

针对"listofobjs[2].Color"这类格式的字符串,用正则表达式可以精准提取索引和属性名:

using System.Text.RegularExpressions;

var expression = "listofobjs[2].Color";
var regex = new Regex(@"^(\w+)\[(\d+)\]\.(\w+)$");
var match = regex.Match(expression);

if (!match.Success)
{
    throw new FormatException("表达式格式不正确");
}

// 提取关键信息
var index = int.Parse(match.Groups[2].Value);
var propertyName = match.Groups[3].Value;

2. 获取集合中指定索引的对象

基于已拿到的List<obj>集合,直接通过索引访问目标对象:

if (index < 0 || index >= listofobjs.Count)
{
    throw new IndexOutOfRangeException("索引超出集合范围");
}

var targetObj = listofobjs[index];

3. 反射动态获取属性值

用反射机制读取对象的指定属性值:

using System.Reflection;

var propertyInfo = targetObj.GetType().GetProperty(propertyName);
if (propertyInfo == null)
{
    throw new ArgumentException($"对象不存在名为{propertyName}的属性");
}

var propertyValue = propertyInfo.GetValue(targetObj);
// propertyValue即为listofobjs[2].Color的值

完整整合示例

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;

public class obj
{
    public string Color { get; set; }
}

class Program
{
    static void Main()
    {
        // 模拟目标集合
        var listofobjs = new List<obj>
        {
            new obj { Color = "Red" },
            new obj { Color = "Green" },
            new obj { Color = "Blue" }
        };

        var expression = "listofobjs[2].Color";
        var result = GetPropertyValue(listofobjs, expression);
        Console.WriteLine(result); // 输出: Blue
    }

    static object GetPropertyValue(List<obj> targetList, string expression)
    {
        var regex = new Regex(@"^(\w+)\[(\d+)\]\.(\w+)$");
        var match = regex.Match(expression);

        if (!match.Success)
        {
            throw new FormatException("表达式格式不符合要求");
        }

        var index = int.Parse(match.Groups[2].Value);
        var propertyName = match.Groups[3].Value;

        if (index < 0 || index >= targetList.Count)
        {
            throw new IndexOutOfRangeException("索引超出集合有效范围");
        }

        var targetObj = targetList[index];
        var propertyInfo = targetObj.GetType().GetProperty(propertyName);

        if (propertyInfo == null)
        {
            throw new ArgumentException($"对象无此属性: {propertyName}");
        }

        return propertyInfo.GetValue(targetObj);
    }
}

补充优化建议

  • 若需支持更复杂的表达式(如多层属性嵌套),可改用表达式树(Expression类)构建访问逻辑,性能优于反射。
  • 频繁调用时,建议缓存反射获取的PropertyInfo,减少重复反射的性能开销。

内容的提问来源于stack exchange,提问作者desiredness

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 16:41:13