[C.C++] C#之静态类

189 0
Honkers 2026-6-30 08:06:40 来自手机 | 显示全部楼层 |阅读模式

核心明白什么是静态static
产生在程序启动之前,消失程序结束之后,全局存在
不需要实例化,就可以使用

13C#之静态类

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. namespace C_之静态类
  11. {
  12. public partial class Form1 : Form
  13. {
  14. public Form1()
  15. {
  16. InitializeComponent();
  17. }
  18. private void button1_Click(object sender, EventArgs e)
  19. {
  20. // 使用(不需要实例化)
  21. Person.Speak();
  22. }
  23. }
  24. /// <summary>
  25. /// 静态类(一 定义)
  26. /// </summary>
  27. public static class Person
  28. {
  29. // 字段 需要静态 (static 这个变量 类 方法 生成在程序启动之前,消失程序关闭之后,全局唯一存在)
  30. public static string name = "张三";
  31. public static void Speak()
  32. {
  33. MessageBox.Show(name+"讲话");
  34. }
  35. }
  36. }
复制代码

C# 静态类(Static Classes)完全指南

静态类是C#中一种特殊的类类型,它提供了一种将工具方法、常量和其他共享数据组织在一起的方式,而无需实例化对象。本文将深入探讨静态类的各个方面,包括其定义、特性、使用场景、最佳实践以及与相关概念的对比。

什么是静态类?

静态类是使用static关键字修饰的类,它不能被实例化,只能通过类名直接访问其成员。静态类通常用于封装与特定类型无关但需要全局访问的功能。

基本语法

  1. public static class MathUtilities
  2. {
  3. // 静态字段
  4. public const double Pi = 3.141592653589793;
  5. // 静态方法
  6. public static double CalculateCircleArea(double radius)
  7. {
  8. return Pi * radius * radius;
  9. }
  10. // 静态属性
  11. public static string Version => "1.0.0";
  12. }
复制代码

静态类的核心特性

  1. 不能实例化:静态类没有构造函数(也不能有实例构造函数)
  2. 自动为密封和抽象:静态类隐式为sealed(不能被继承)和abstract(不能被实例化)
  3. 只能包含静态成员:所有字段、方法、属性等都必须声明为static
  4. 不能包含实例成员:尝试添加非静态成员会导致编译错误
  5. 编译时常量:静态类中的常量会在编译时解析

静态类的常见用途

1. 数学和实用工具类

这是静态类最常见的用途之一,用于封装不依赖于特定实例的通用功能。

示例:自定义数学工具类

  1. public static class AdvancedMath
  2. {
  3. // 常量
  4. public const double E = 2.718281828459045;
  5. // 静态方法
  6. public static double Factorial(int n)
  7. {
  8. if (n < 0) throw new ArgumentException("n must be non-negative");
  9. if (n == 0) return 1;
  10. double result = 1;
  11. for (int i = 1; i <= n; i++)
  12. {
  13. result *= i;
  14. }
  15. return result;
  16. }
  17. public static double LogBase(double value, double baseValue)
  18. {
  19. if (value <= 0 || baseValue <= 0 || baseValue == 1)
  20. throw new ArgumentException("Invalid arguments for logarithm");
  21. return Math.Log(value) / Math.Log(baseValue);
  22. }
  23. // 静态属性
  24. public static int MaxIntegerValue => int.MaxValue;
  25. }
  26. // 使用示例
  27. class Program
  28. {
  29. static void Main()
  30. {
  31. Console.WriteLine($"5! = {AdvancedMath.Factorial(5)}");
  32. Console.WriteLine($"Log2(8) = {AdvancedMath.LogBase(8, 2)}");
  33. Console.WriteLine($"Max int value: {AdvancedMath.MaxIntegerValue}");
  34. }
  35. }
复制代码

2. 配置和常量存储

静态类可用于存储应用程序配置或常量值。

示例:应用程序配置类

  1. public static class AppConfig
  2. {
  3. // 配置常量
  4. public static string DatabaseConnectionString =>
  5. "Server=myServer;Database=myDB;Trusted_Connection=True;";
  6. public static int MaxRetryAttempts => 3;
  7. public static TimeSpan Timeout => TimeSpan.FromSeconds(30);
  8. // 静态方法(用于验证配置)
  9. public static bool IsValidConnectionString(string connectionString)
  10. {
  11. return !string.IsNullOrWhiteSpace(connectionString) &&
  12. connectionString.Contains("Server=") &&
  13. connectionString.Contains("Database=");
  14. }
  15. }
复制代码

3. 扩展方法容器

静态类常用于存放扩展方法(尽管扩展方法本身是实例方法,但它们必须定义在静态类中)。

  1. public static class StringExtensions
  2. {
  3. public static bool IsNullOrEmpty(this string str)
  4. {
  5. return string.IsNullOrEmpty(str);
  6. }
  7. public static string Reverse(this string str)
  8. {
  9. if (str == null) throw new ArgumentNullException(nameof(str));
  10. char[] charArray = str.ToCharArray();
  11. Array.Reverse(charArray);
  12. return new string(charArray);
  13. }
  14. public static string Truncate(this string str, int maxLength)
  15. {
  16. if (str == null) throw new ArgumentNullException(nameof(str));
  17. if (maxLength < 0) throw new ArgumentOutOfRangeException(nameof(maxLength));
  18. return str.Length <= maxLength ? str : str.Substring(0, maxLength);
  19. }
  20. }
  21. // 使用示例
  22. class Program
  23. {
  24. static void Main()
  25. {
  26. string test = "Hello, World!";
  27. Console.WriteLine(test.Reverse()); // 输出: !dlroW ,olleH
  28. Console.WriteLine(test.Truncate(5)); // 输出: Hello
  29. Console.WriteLine("".IsNullOrEmpty()); // 输出: True
  30. }
  31. }
复制代码

4. 工厂方法模式

静态类可用于实现工厂方法模式,创建特定类型的实例。

  1. public static class LoggerFactory
  2. {
  3. public static ILogger CreateFileLogger(string filePath)
  4. {
  5. return new FileLogger(filePath);
  6. }
  7. public static ILogger CreateConsoleLogger()
  8. {
  9. return new ConsoleLogger();
  10. }
  11. public static ILogger CreateNullLogger()
  12. {
  13. return new NullLogger();
  14. }
  15. }
  16. // 接口定义
  17. public interface ILogger
  18. {
  19. void Log(string message);
  20. }
  21. // 具体实现(简化版)
  22. class FileLogger : ILogger { /*...*/ }
  23. class ConsoleLogger : ILogger { /*...*/ }
  24. class NullLogger : ILogger { /*...*/ }
  25. // 使用示例
  26. class Program
  27. {
  28. static void Main()
  29. {
  30. ILogger logger = LoggerFactory.CreateFileLogger("app.log");
  31. logger.Log("Application started");
  32. }
  33. }
复制代码

静态类与相关概念的对比

1. 静态类 vs 实例类

特性静态类实例类
实例化不能实例化可以实例化
成员只能包含静态成员可以包含实例和静态成员
继承不能被继承可以被继承
生命周期应用程序域生命周期实例生命周期
线程安全通常需要手动实现线程安全每个实例有自己的状态

2. 静态类 vs 单例模式

特性静态类单例模式
实例化不能实例化有一个私有实例,通过公共方法访问
继承不能被继承可以被继承(通过修改模式)
延迟初始化不支持支持延迟初始化
测试难以模拟(mock)相对容易模拟
多态性不支持支持

静态类的最佳实践

  1. 命名规范:为静态类使用描述性名称,通常以"Utility"、“Helper”、"Factory"等后缀结尾

  2. 线程安全:如果静态类包含可变状态,确保实现线程安全

    1. public static class ThreadSafeCounter
    2. {
    3. private static int _count = 0;
    4. private static readonly object _lock = new object();
    5. public static int Increment()
    6. {
    7. lock (_lock)
    8. {
    9. return ++_count;
    10. }
    11. }
    12. public static int GetCount()
    13. {
    14. lock (_lock)
    15. {
    16. return _count;
    17. }
    18. }
    19. }
    复制代码
  3. 避免过度使用:静态类会创建全局状态,可能导致代码难以测试和维护

  4. 单一职责原则:每个静态类应该只负责一个特定的功能领域

  5. 文档注释:为静态类和方法添加清晰的XML文档注释

  6. 常量命名:常量使用全大写命名,单词间用下划线分隔

    1. public static class AppConstants
    2. {
    3. public const int MAX_USERS = 100;
    4. public const string DEFAULT_THEME = "Light";
    5. }
    复制代码

静态类的局限性

  1. 不能实现接口:静态类不能实现接口,因为接口需要实例来调用

  2. 不能作为基类:静态类不能作为其他类的基类

  3. 依赖注入困难:静态类难以与依赖注入框架集成

  4. 测试挑战:静态类中的方法难以模拟(mock),影响单元测试

完整示例:综合应用

下面是一个综合使用静态类的完整示例,展示了静态类在配置管理、实用工具方法和扩展方法中的应用:

  1. // 配置静态类
  2. public static class AppSettings
  3. {
  4. public static string ApiBaseUrl => "https://api.example.com/v1";
  5. public static int MaxConcurrentRequests => 10;
  6. public static TimeSpan RequestTimeout => TimeSpan.FromSeconds(30);
  7. public static void Validate()
  8. {
  9. if (string.IsNullOrWhiteSpace(ApiBaseUrl))
  10. throw new InvalidOperationException("API base URL is not configured");
  11. if (MaxConcurrentRequests <= 0)
  12. throw new InvalidOperationException("Max concurrent requests must be positive");
  13. }
  14. }
  15. // 实用工具静态类
  16. public static class StringUtilities
  17. {
  18. public static string FormatAsUrl(this string input)
  19. {
  20. if (string.IsNullOrWhiteSpace(input))
  21. return string.Empty;
  22. return input
  23. .Trim()
  24. .ToLowerInvariant()
  25. .Replace(" ", "-")
  26. .Replace("__", "-") // 清理多余的下划线
  27. .Replace("__", "-")
  28. .Replace("__", "-");
  29. }
  30. public static bool IsValidEmail(string email)
  31. {
  32. if (string.IsNullOrWhiteSpace(email))
  33. return false;
  34. try
  35. {
  36. var addr = new System.Net.Mail.MailAddress(email);
  37. return addr.Address == email;
  38. }
  39. catch
  40. {
  41. return false;
  42. }
  43. }
  44. }
  45. // 扩展方法静态类
  46. public static class DateTimeExtensions
  47. {
  48. public static string ToRelativeTime(this DateTime dateTime)
  49. {
  50. var timeSpan = DateTime.Now - dateTime;
  51. if (timeSpan <= TimeSpan.FromSeconds(60))
  52. return $"{timeSpan.Seconds} seconds ago";
  53. if (timeSpan <= TimeSpan.FromMinutes(60))
  54. return $"{timeSpan.Minutes} minutes ago";
  55. if (timeSpan <= TimeSpan.FromHours(24))
  56. return $"{timeSpan.Hours} hours ago";
  57. if (timeSpan <= TimeSpan.FromDays(30))
  58. return $"{timeSpan.Days} days ago";
  59. return dateTime.ToString("yyyy-MM-dd");
  60. }
  61. }
  62. // 使用示例
  63. class Program
  64. {
  65. static void Main()
  66. {
  67. // 验证配置
  68. AppSettings.Validate();
  69. // 使用字符串工具
  70. string rawUrl = " My Page Title ";
  71. string formattedUrl = rawUrl.FormatAsUrl();
  72. Console.WriteLine($"Formatted URL: {formattedUrl}"); // 输出: my-page-title
  73. // 使用扩展方法
  74. DateTime pastDate = DateTime.Now.AddDays(-5);
  75. Console.WriteLine($"5 days ago: {pastDate.ToRelativeTime()}"); // 输出: 5 days ago
  76. // 验证邮箱
  77. string email = "test@example.com";
  78. Console.WriteLine($"{email} is valid: {StringUtilities.IsValidEmail(email)}"); // 输出: True
  79. }
  80. }
复制代码

结论

静态类是C#中一个强大但需要谨慎使用的特性。它们非常适合封装与特定类型无关的通用功能、配置和工具方法。通过合理使用静态类,你可以:

  1. 提高代码的可读性和可维护性,将相关功能组织在一起
  2. 提供全局可访问的工具方法,而无需实例化对象
  3. 创建不可变的配置容器
  4. 实现工厂方法模式

然而,也要注意静态类的局限性:

  • 它们创建全局状态,可能导致代码难以测试和维护
  • 不能实现接口或多态性
  • 难以与依赖注入框架集成

在决定使用静态类之前,评估项目需求和团队工作流程,确保它能真正为你的项目带来价值。对于需要状态或依赖注入的场景,考虑使用单例模式或其他设计模式替代静态类。

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2026 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行