繁体   English   中英

我不知道如何在 xamarin 上连续运行一个函数

[英]I don't know how i can run a function continuously on xamarin

你好,这是我第一次用 C# 编程,也是第一次使用 xamarin,我在 xamarin 上制作了这段代码作为第一个项目。

using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace Counter
{
    public partial class MainPage : ContentPage
    {
        private int count = 0;
        private int squared = 0;
        private double sqroot = 0;
        private int milliseconds = 500;
        private bool direction = true;
        public MainPage()
        {
            InitializeComponent();
        }

        private void IncrementCounterClicked(object sender, EventArgs e)
        {
            direction = true;

        }

        private void Button_Clicked(object sender, EventArgs e)
        {
            direction = false;

        }

        private void Auto_increment()
        {
            if (direction == true)
                count++;
            else
                count--;

            squared = count * count;
            sqroot = Math.Sqrt(count);
            CounterLabel.Text = count.ToString();
            Squared.Text = squared.ToString();
            Sqroot.Text = sqroot.ToString();
            Task.Delay(1000);

        }

    }
}

每次代码执行时如何运行 Auto_Increment 函数? 如果重要的话,我会在 android 设备上使用它。 还有我如何只显示双变量的前 2 位数字?

据我所知,如果您想将它用于使用 xamarin 构建的 android 应用程序,您实际上可以使用下面给出的生命周期函数:

protected override void OnResume()
{
    #CALL_YOUR_FUNCTION_HERE
}

并舍入双精度值,您可以使用下面给出的舍入方法:

Math.Round(#Value_to_be_rounded, #number_of_decimal_places)
For instance: Math.Round(3.56, 1) will give you 3.5

希望这可以帮助。

尝试这样做。 请注意,此解决方案不是一个好的解决方案。 您必须在Auto_increment()控制这个无限循环,或者找到另一种以更Auto_increment()方式连续运行它的方法。 添加一个新按钮并将while(true)替换为您通过单击新按钮控制的while(yourBoolean) (就像您已经为增量所做的那样)。

public partial class MainPage : ContentPage
{
    private int count = 0;
    private int squared = 0;
    private double sqroot = 0;
    private int milliseconds = 500;
    private bool direction = true;

    public MainPage()
    {
        InitializeComponent();

        Auto_increment();
    }

    private void IncrementCounterClicked(object sender, EventArgs e)
    {
        direction = true;

    }

    private void Button_Clicked(object sender, EventArgs e)
    {
        direction = false;

    }

    private void Auto_increment()
    {
        while (true) {

            if (direction == true)
                count++;
            else
                count--;

            squared = count * count;
            sqroot = Math.Sqrt(count);
            CounterLabel.Text = count.ToString();
            Squared.Text = squared.ToString();
            Sqroot.Text = sqroot.ToString();
            Task.Delay(1000);
        }
    }
}

PS:另请注意,您应该遵循代码中的命名指南 在您的情况下,重命名您的私有方法AutoIncrement()

希望这会帮助你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM