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

C#新手求助:如何在不同方法间传递变量修改后的数据?

解决C#中BuyX方法变量修改结果回传的问题

C#里double是值类型,默认采用值传递——方法里修改的只是参数的副本,上层调用方法里的原始变量不会被改变。要把BuyX里修改后的sp、bstr、bstrCost传递回上层,有两种常用方案:


方案一:使用ref引用参数

通过ref关键字将参数改为引用传递,方法里对参数的修改会直接作用于上层的原始变量。

修改后的代码:

if (key == 'B')
{
    // 调用时给需要回传的参数加上ref
    BuyX(ref bstr, ref bstrCost, ref sp, 10);
}

// 方法参数前加上ref关键字
public static void BuyX(ref double bstr, ref double bstrCost, ref double sp, double z) 
{
    double currentCost = 0;
    double totalCost = 0;
    double repeat = 0;
    currentCost = bstrCost;
    
    while (repeat < z - 1)
    {
        totalCost = totalCost + currentCost;
        currentCost = (currentCost * (1.25 + (0.005 * (bstr - 1 + repeat))));
        repeat = repeat + 1;
    }
    
    totalCost = totalCost + currentCost;
    Console.WriteLine(totalCost);
    
    if (sp >= totalCost)
    {
        // 取消注释,直接修改引用参数
        sp = sp - totalCost;
        bstr = bstr + z;
        bstrCost = currentCost;
    }
}

方案二:封装返回结果为自定义类型

如果不想用ref参数,可以创建一个类/结构体来封装需要返回的三个值,让BuyX方法返回这个类型的实例,上层调用后再更新原始变量。

修改后的代码:

// 定义一个类存储返回结果
public class BuyResult
{
    public double UpdatedSp { get; set; }
    public double UpdatedBstr { get; set; }
    public double UpdatedBstrCost { get; set; }
    public bool IsSuccess { get; set; } // 标记是否执行了变量修改逻辑
}

if (key == 'B')
{
    var result = BuyX(bstr, bstrCost, sp, 10);
    // 如果修改逻辑执行了,更新上层变量
    if (result.IsSuccess)
    {
        sp = result.UpdatedSp;
        bstr = result.UpdatedBstr;
        bstrCost = result.UpdatedBstrCost;
    }
}

// 修改方法返回类型为BuyResult
public static BuyResult BuyX(double bstr, double bstrCost, double sp, double z) 
{
    double currentCost = 0;
    double totalCost = 0;
    double repeat = 0;
    currentCost = bstrCost;
    
    while (repeat < z - 1)
    {
        totalCost = totalCost + currentCost;
        currentCost = (currentCost * (1.25 + (0.005 * (bstr - 1 + repeat))));
        repeat = repeat + 1;
    }
    
    totalCost = totalCost + currentCost;
    Console.WriteLine(totalCost);
    
    if (sp >= totalCost)
    {
        // 返回修改后的结果
        return new BuyResult
        {
            UpdatedSp = sp - totalCost,
            UpdatedBstr = bstr + z,
            UpdatedBstrCost = currentCost,
            IsSuccess = true
        };
    }
    // 不满足条件时返回默认结果
    return new BuyResult { IsSuccess = false };
}

两种方案里,方案一更直接,适合简单场景;方案二更灵活,尤其是需要返回多个值且不想用ref/out的时候。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 01:27:15