c# - 以下示例代码中 AttemptController 中的静态字段是什么意思?
问题描述
我是 C# 的新手,正在尝试学习静态关键字。我不明白为什么我们需要两次初始化静态字段。据我了解,静态字段在程序执行期间保留该值。
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; } } }
推荐阅读
- algorithm - 通过用另一个函数替换一个递归来优化排序算法
- c - 使用在 C 中执行子字符串的函数时字符串解析失败
- laravel - 为什么 Eloquent 模型“引导”方法在 Laravel 7.x 上没有触发?
- javascript - 获取当前电子邮件的 URL 谷歌脚本
- docker - Docker-Compose:如何依赖另一个网络上的容器?即使网络已链接,我也收到错误提示容器“未定义”
- javascript - 如何更改百里香中链接(href 文本)的颜色?
- php - 需要函数来在 PHP 中四舍五入价格
- c# - 如何使用 C# MongoDB 驱动程序编写一个嵌套对象属性不能相等的强类型过滤器?
- wordpress - 在 woocommerce_thankyou 页面的 API 中保存的订单
- django - django-cors-headers 不适用于补丁方法