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

C# 如何通过字符串路径间接访问对应位置的字符串变量值

C# 本身没有原生支持直接用字符串作为变量访问路径取值的语法,你可以通过两种方案实现需求,优先推荐第一种:

方案1:重构TextLibrary结构(最优)

直接把分组改成字典存储,既保留原有的静态访问方式,又支持动态按分组名取值,性能和可维护性都是最好的:

  1. 调整TextLibrary类定义:
public class TextLibrary
{
    // 存储所有分组的字典,key为分组名
    public Dictionary<string, Group> Groups { get; set; } = new Dictionary<string, Group>();

    // 原有静态分组属性保留,兼容旧代码
    public Group Group1
    {
        get => Groups[nameof(Group1)];
        set => Groups[nameof(Group1)] = value;
    }
    // 其他Group2、Group3等分组同理定义
}

// 分组类和消息类定义示例
public class Group
{
    public List<MessageItem> Messages { get; set; }
}
public class MessageItem
{
    public string Message { get; set; }
}
  1. 调用逻辑直接简化为:
for (int i = 0; i < 10; i++)
{
    Label[i].Text = Globals.TextLibrary.Groups[this.InstanceName].Messages[i].Message;
}

方案2:反射实现动态路径解析

如果无法修改TextLibrary的原有结构,可以用反射实现你需要的stringToName方法:

  1. 封装通用路径取值方法:
public static object GetValueByPath(object rootObj, string propertyPath)
{
    object current = rootObj;
    string[] pathSegments = propertyPath.Split('.');
    
    foreach (string segment in pathSegments)
    {
        if (current == null) return null;
        // 处理数组/列表索引格式,比如Messages[0]
        if (segment.Contains('['))
        {
            int bracketStart = segment.IndexOf('[');
            string propName = segment.Substring(0, bracketStart);
            int index = int.Parse(segment.Substring(bracketStart + 1).TrimEnd(']'));
            
            var listProp = current.GetType().GetProperty(propName);
            if (listProp == null) return null;
            object list = listProp.GetValue(current);
            // 取索引对应的元素
            current = list.GetType().GetProperty("Item").GetValue(list, new object[] { index });
        }
        else
        {
            // 普通属性取值
            var prop = current.GetType().GetProperty(segment);
            if (prop == null) return null;
            current = prop.GetValue(current);
        }
    }
    return current;
}
  1. 调用方式:
for (int i = 0; i < 10; i++)
{
    string path = $"TextLibrary.{this.InstanceName}.Messages[{i}].Message";
    Label[i].Text = GetValueByPath(Globals, path) as string;
}

注意事项

  • 反射方案性能远低于直接属性访问,频繁调用建议缓存反射得到的属性信息
  • 建议增加空值判断和异常捕获,避免分组名拼写错误、索引越界时触发未处理异常
  • 如果你的分组是类的字段而非属性,把代码中的GetProperty替换为GetField即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 07:36:04