.Net中的计数比较

本文关键字:比较 Net | 更新日期: 2023-09-27 18:10:54

我在c#中编写了一个方法来获取表的计数,并将计数保存在设置属性中。

public static bool CompareCount(int? currentCount)
{
    Properties.Settings.Default.Count = (int)currentCount;
    Properties.Settings.Default.Save();
    if (currentCount < Properties.Settings.Default.Count)
    {
        return false;
    }
    else
    {
        return true;
    }
}   

第一次如果返回的计数是20。我会把它保存在设置中,我不会把它和以前的计数进行比较。第二次打开时,我想将当前计数与上次在设置中保存的计数进行比较。上面的方法应该是第一次分配当前计数。但第二次它会比较。

提前谢谢。

.Net中的计数比较

首先,考虑一下如果参数为null,则将要进入intint?强制转换时会发生什么。如果以后不使用可为null的参数,那么使用它是没有意义的。您应该将参数类型更改为int,或者可以这样做:

Properties.Settings.Default.Count = currentCount ?? 0;

然后,该方法将始终返回true,因为if条件始终为false-还记得您将Properties.Settings.Default.Count设置为currentCount吗?那么它怎么会比currentCount大呢?

你需要自己定义如何确定"第一次"answers"第二次"。确定该方法是否是第一次运行的条件是什么?对于下面的代码,我假设Properties.Settings.Default.Count有一些默认值,可以帮助您确定该方法是否是第一次运行。

然后,根据你所说的,你的代码应该是这样的:

public static bool CompareCount(int? currentCount)
{
    int countValue = currentCount ?? 0;
    if (Properties.Settings.Default.Count == <some default value>)
    {    
        Properties.Settings.Default.Count = (int)currentCount;
        Properties.Settings.Default.Save();
    }
    else
    {
        return currentCount >= Properties.Settings.Default.Count;
    }
}   

您在实现它时遇到了什么问题?你手头已经有了所有的积木。只需正确地重新排序即可。

如果问题是设置中定义的"int Count"默认为"0",您可以将其更改为默认值-1,这样它显然不是以前写的Count。或者,您可以将其更改为int?,使其默认为null。。

让当前找到的Count检查它是否等于默认值(零,或者未找到,或者在未找到时设置自己的值,比如-1(,所以一旦未找到,就不进行比较,否则就比较值。

例如:

public static bool CompareCount(int? currentCount)
{
    int foundCount = ReadFoundCountFromProperties;
    if (foundCount != 0)
    {
      Properties.Settings.Default.Count = (int)currentCount;
      Properties.Settings.Default.Save();
      if (currentCount < foundCount)
       return false;
      return true;
}