为了账号安全,请及时绑定邮箱和手机立即绑定

更改方法后如何解决 int 值重置

更改方法后如何解决 int 值重置

C#
米脂 2021-10-24 19:23:51
我在我的方法中设置了一个 int 值GetDays,然后我想在里面使用这个值,GetRiskAssement()但一旦我回到这个方法,它就会更改为默认值 0。我想设置intDays并使其保持不变,直到我GetDays再次运行该方法。public class RiskA{    int accountId;    static int intDays;    bool stop;    List<int> DateVehicleList = new List<int>();    public List<DisplayableRiskAssement> DisplayableRiskAssement { get; private set; }    public RiskAssement()    {        accountId = 461;        DisplayableRiskAssement = GetRiskAssement();    }    List<DisplayableRiskAssement> GetRiskAssement()    {       //Additional code here than runs through a load of records        if(riskAssement.InUK == false)        {            GetVehiclesNotInUK(riskAssement.VehicleID);            riskAssement.IntDaysSinceUK = intDays;        }        return riskAssesments;    }    protected void GetVehiclesNotInUK(int VehicleID)     {        //Code here that creates DateVehicleList        GetDays(DateVehicleList, intDays);    }    private static int GetDays(List<int> DateVehicleList, int intDays)     {        using (aEntities db = new aEntities())        {            foreach (var item in DateVehicleList)            {                var qryDate = (from a in db.ev                               where a.evID == item                               select a.sysdatetime).Single();                string strDate = qryDate.ToString();                DateTime oldDate = DateTime.Parse(strDate);                TimeSpan t = DateTime.Now - oldDate;                double doubleDays = t.TotalDays;                intDays = Convert.ToInt32(doubleDays);            }        }        DateVehicleList.Clear();        return intDays;    }}
查看完整描述

3 回答

?
尚方宝剑之说

TA贡献1788条经验 获得超4个赞

在 C# 中,参数可以通过值或通过引用传递给参数。为了您的GetDays方法,你已经通过DateVehicleList参考,并且intDays的价值。除非您在其中分配返回值,否则您之前的类对象中的intDays值将不会更新。


protected void GetVehiclesNotInUK(int VehicleID) 

{

    //Code here that creates DateVehicleList

    intDays = GetDays(DateVehicleList, intDays);

不是它会像你预期的那样工作,干杯!


查看完整回答
反对 回复 2021-10-24
?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

您的方法GetDays应该对类变量进行操作,而不是对您传递的参数进行操作。

如果您希望该方法使用类变量,只需从此方法中删除参数:

private static int GetDays(){...}


查看完整回答
反对 回复 2021-10-24
?
九州编程

TA贡献1785条经验 获得超4个赞

int 是 Primitive 类型,所以默认情况下它是 0。所以当你的对象被初始化时,你的构造函数调用 GetRiskAssement() 方法,并且该方法使用的 intDay 尚未在你的 GetDays() 方法中设置,这就是它向你返回 0 的原因。您可以使用 intDay 作为您的类属性,并对其进行 getter 和 setter,并且您的 getDays() 方法适用于您的类属性而不是参数。


private static int intDay;

public static int getIntDay()

{

    return intDay;

}

public static void setIntDay(int intDay)

{

    this.intDay = intDay;

}

你的函数应该看起来像。


private static int GetDays()

{

    //your code goes here

}

希望这对你有帮助。


查看完整回答
反对 回复 2021-10-24
  • 3 回答
  • 0 关注
  • 243 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信