gpt4 book ai didi

c# - 以下示例代码中 AttemptController 中的静态字段是什么意思?

转载 作者:行者123 更新时间:2023-11-30 15:52:59 25 4
gpt4 key购买 nike

我是 C# 的新手,正在尝试学习 static 关键字。我不明白为什么我们需要两次初始化静态字段。根据我的理解,静态字段在程序执行期间保留值。

class Program
{
static void Main(string[] args)
{

AttemptController Obj = new AttemptController(3, 2);
Console.WriteLine("Maximum: {0}", AttemptController.MaxAttempts);
Console.WriteLine("Warning: {0}", AttemptController.WarningAttempts);
Console.WriteLine("Threshold: {0}", AttemptController.Threshold);

AttemptController Obj1 = new AttemptController(7, 5);
Console.WriteLine("Maximum: {0}", AttemptController.MaxAttempts);
Console.WriteLine("Warning: {0}", AttemptController.WarningAttempts);
Console.WriteLine("Threshold: {0}", AttemptController.Threshold);
Console.ReadLine();
}

class AttemptController
{
internal static int MaxAttempts;
internal static int WarningAttempts;
internal static int Threshold;

public AttemptController(int a, int b)
{
MaxAttempts = a;
WarningAttempts = b;
Threshold = MaxAttempts - WarningAttempts;
}
}
}

最佳答案

因此,提出了一些更改建议:

  • 使类静态化
  • 去掉构造函数,因为静态类不能有实例构造函数。
  • 添加一个名为 init 的新方法,仅用于演示目的。

    using System;

    namespace ConsoleApp4
    {
    internal class Program
    {
    private static void Main(string[] args)
    {
    AttemptController.Init(3, 2);
    Console.WriteLine("Maximum: {0}", AttemptController.MaxAttempts);
    Console.WriteLine("Warning: {0}", AttemptController.WarningAttempts);
    Console.WriteLine("Threshold: {0}", AttemptController.Threshold);

    AttemptController.Init(7, 5);
    Console.WriteLine("Maximum: {0}", AttemptController.MaxAttempts);
    Console.WriteLine("Warning: {0}", AttemptController.WarningAttempts);
    Console.WriteLine("Threshold: {0}", AttemptController.Threshold);
    Console.ReadLine();
    }
    }

    public static class AttemptController
    {
    internal static int MaxAttempts;
    internal static int WarningAttempts;
    internal static int Threshold;



    public static void Init(int a, int b)
    {
    MaxAttempts = MaxAttempts + a;
    WarningAttempts = WarningAttempts + b;
    Threshold = MaxAttempts - WarningAttempts;
    }
    }
    }

关于c# - 以下示例代码中 AttemptController 中的静态字段是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53475315/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com