通过方法调用

时间:2018-03-26 15:12:34

标签: c# .net

这闻起来像我的变量的范围问题,但移动它似乎没有帮助。这是一个非常简单的例子。我创建了currentDay变量。我设定了它的价值。然后我调用另一个方法来改变currentDay的值,但它永远不会改变。就在周一早上失明?

void Main()
{
    SetScheduleTicketsDate();
}

public static void SetScheduleTicketsDate()
{
    DateTime currentDay = DateTime.Now;
    SchedulePatchGroup(currentDay);
    Console.WriteLine(currentDay);
}

private static void SchedulePatchGroup(DateTime currentDay)
{
    currentDay = currentDay.AddDays(10);
}

1 个答案:

答案 0 :(得分:5)

除非您使用refout,否则分配参数不会传播给来电者。

通常这是代码气味;你的方法应该只是返回更新的对象。

public static void SetScheduleTicketsDate()
{
    DateTime currentDay = DateTime.Now;
    currentDay = SchedulePatchGroup(currentDay);
    Console.WriteLine(currentDay);
}

private static DateTime SchedulePatchGroup(DateTime currentDay)
{
    return currentDay.AddDays(10);
}

由于DateTime是值类型,因此仅使用currentDay.AddDays(10)将不会执行任何操作; AddDays不会改变当前实例,而是返回一个新实例。