【问题标题】:C# function that sets a bool true after a period of time在一段时间后将布尔值设置为 true 的 C# 函数
【发布时间】:2020-02-07 18:37:06
【问题描述】:

是否可以编写一个接收 bool 和 float 并在一段时间后(由 float 确定)重置该 bool 的 C# 函数?

特别是我要求这样的东西:

void reset(bool a, float b){

    ... After a certain time period determined by b
    a = true;

}

然后要重置任何 bool,我可以调用 reset,传入一个 bool 和一个浮点数,这决定了 bool 被重置所需的时间

这需要适用于任何布尔,而不是一个特定的布尔。谢谢。

【问题讨论】:

  • 这似乎是XY Problem,您能否解释一下导致您在此解决方案尝试中思考的问题是什么?
  • 这似乎是一个经典的 XY 问题。你想解决什么问题?你能接受屏蔽解决方案吗?

标签: c#


【解决方案1】:

没有足够的信息来提供完整的解决方案,但这里有一些想法:

  1. 通过引用传递布尔值。请查看传递值类型参数(C# 编程指南)中的Passing Value Types by Reference
  2. 等待:a) 使用 await Task.Delay b) 使用计时器 c) 启动一个新任务,不要在这里等待

这是一种方法:

async Task ChangeMeAfter(ref bool makeTrue, float afterSeconds)
{
 await Task.Delay(TimeSpan.FromSeconds(afterSeconds);
 makeTrue = true;
}

【讨论】:

    【解决方案2】:

    为了在方法执行后检查该 bool 值,您需要将其作为参考传递(在这里查看如何做到这一点:C# Pointers in a Method's arguments?)。

    在方法体中,可以使用计时器来确定何时编辑布尔值(使用第二个参数):https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=netframework-4.8

    【讨论】:

      【解决方案3】:
      class Program
      {
          static void Main(string[] args)
          {
              reset(false, 228.10803f);
          }
      
          public static void reset(bool a, float b)
          {
              float totalSeconds = b;
              Thread.Sleep(Convert.ToInt32(b));
              if(a)
              {
                  a = false;
              }
              else
              {
                  a = true;
              }
              Console.WriteLine("Value should be reset after certain time. Bool value is {0}",a);
              Console.ReadLine();
          }
      }
      

      【讨论】:

      • totalSeconds 变量从未使用过,我也会使用a = !a; 而不是if else 语句。
      • 这只会改变本地a。
      • 您可以删除 totalSeconds 变量,但该解决方案适用于您的问题
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-08
      • 2014-01-19
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多