首页 > 解决方案 > 我不知道如何在 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?如果重要的话,我会在安卓设备上使用它。还有我如何只显示双变量的前 2 位数字?

标签: c#androidxamarin

解决方案


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

protected override void OnResume()
{
    #CALL_YOUR_FUNCTION_HERE
}

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

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

希望这可以帮助。


推荐阅读