以下示例代码中AttemptController中静态字段的含义是什么?

时间:2018-11-26 05:42:34

标签: c# oop static

我是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;
        }
    }
}

2 个答案:

答案 0 :(得分:2)

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

  • 将类设为静态
  • 摆脱构造函数,因为静态类不能具有实例构造函数。
  • 添加一个名为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;
            }
        }
    }
    

答案 1 :(得分:1)

因为您在构造函数方法中设置了MaxAttemptsWarningAttemptsThreshold字段。

使用AttemptController Obj = new AttemptController(3, 2);时将设置该值。

使用时将设置MaxAttempts = 3WarningAttempts = 2

AttemptController Obj = new AttemptController(3, 2);

使用时将设置MaxAttempts = 7WarningAttempts = 5

AttemptController Obj1 = new AttemptController(7, 5);

static字段允许所有实例使用相同的字段值。