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

C#中如何动态拼接变量名批量为Quote类的qty系列属性赋值

方案1:可修改Quote类的最优实现

直接给Quote类添加索引器,保留原有属性兼容现有逻辑,性能最高、易维护:

public class Quote
{
    public float qty1 { get; set; }
    public float qty2 { get; set; }
    public float qty3 { get; set; }
    public float qty4 { get; set; }

    // 添加索引器支持下标访问
    public float this[int index]
    {
        get => index switch
        {
            0 => qty1,
            1 => qty2,
            2 => qty3,
            3 => qty4,
            _ => throw new IndexOutOfRangeException()
        };
        set
        {
            switch (index)
            {
                case 0: qty1 = value; break;
                case 1: qty2 = value; break;
                case 2: qty3 = value; break;
                case 3: qty4 = value; break;
                default: throw new IndexOutOfRangeException();
            }
        }
    }
}

修改完成后循环可以直接写成:

for (int i = 0; i <= 3; i++)
{
    quote[i] = qty1[i];
}

方案2:无法修改Quote类时用反射实现

如果Quote类为第三方引用无法修改源码,可以通过反射动态获取属性赋值:

for (int i = 0; i <= 3; i++)
{
    var property = typeof(Quote).GetProperty($"qty{i + 1}");
    property.SetValue(quote, qty1[i]);
}

注意:反射性能低于直接赋值,高频调用场景不推荐使用。

固定属性数量的轻量方案

如果属性固定只有4个,也可以用委托数组映射属性,无需修改类也不用反射,兼顾性能和灵活性:

var qtySetters = new Action<float>[]
{
    v => quote.qty1 = v,
    v => quote.qty2 = v,
    v => quote.qty3 = v,
    v => quote.qty4 = v
};
for (int i = 0; i <= 3; i++)
{
    qtySetters[i](qty1[i]);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:36:00