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

如何动态调用Price类静态字段获取Item1与Item2值?

实现动态获取Price类中指定字段的Tuple值

方案一:使用反射(适合字段数量少、对性能要求不高的场景)

直接通过反射根据字段名称获取对应的值,无需提前维护映射关系:

首先定义Price类示例:

public class Price
{
    public Tuple<int, int> applePrice = Tuple.Create(0, 0);
    public Tuple<int, int> bananaPrice = Tuple.Create(1, 2);
    public Tuple<int, int> orangePrice = Tuple.Create(3, 4);
}

在ItemComponent中实现动态取值:

public class ItemComponent
{
    public void FetchPriceValues(string dynamicFieldName)
    {
        var priceObj = new Price();
        var field = typeof(Price).GetField(dynamicFieldName, System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
        
        if (field != null)
        {
            var targetTuple = (Tuple<int, int>)field.GetValue(priceObj);
            int value1 = targetTuple.Item1;
            int value2 = targetTuple.Item2;
            // 后续可使用value1和value2进行业务逻辑处理
        }
        else
        {
            // 处理字段不存在的异常情况
        }
    }
}

方案二:预构建字段映射字典(性能更优,推荐)

提前把字段名和对应的Tuple实例存入字典,后续直接通过键取值,避免反射的性能开销:

修改Price类添加映射字典:

public class Price
{
    public Tuple<int, int> applePrice = Tuple.Create(0, 0);
    public Tuple<int, int> bananaPrice = Tuple.Create(1, 2);
    public Tuple<int, int> orangePrice = Tuple.Create(3, 4);

    // 预定义字段映射字典
    public readonly Dictionary<string, Tuple<int, int>> PriceFieldMap = new()
    {
        { nameof(applePrice), applePrice },
        { nameof(bananaPrice), bananaPrice },
        { nameof(orangePrice), orangePrice }
    };
}

在ItemComponent中快速取值:

public class ItemComponent
{
    public void FetchPriceValues(string dynamicFieldName)
    {
        var priceObj = new Price();
        if (priceObj.PriceFieldMap.TryGetValue(dynamicFieldName, out var targetTuple))
        {
            int value1 = targetTuple.Item1;
            int value2 = targetTuple.Item2;
            // 后续业务逻辑处理
        }
        else
        {
            // 处理字段不存在的异常情况
        }
    }
}

补充说明

如果Price类的字段是静态字段,只需调整反射的BindingFlags为BindingFlags.Public | BindingFlags.Static,字典也改为静态字典即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 22:03:25