C#中单例模式和静态类以及静态方法
时间: 2023-09-24 22:11:31 浏览: 132
单例模式是一种用于创建只有一个实例的类的设计模式。在 C# 中,可以通过私有化构造函数、使用静态成员变量和静态方法实现单例模式。下面是一个简单的 C# 单例模式示例:
```csharp
public sealed class Singleton
{
private static Singleton instance = null;
private static readonly object padlock = new object();
private Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
```
静态类是一种只包含静态成员的类,不能被实例化,而且所有成员都必须是静态的。静态类一般用于存储一些全局变量和常量,以及一些工具方法。下面是一个简单的 C# 静态类示例:
```csharp
public static class Utils
{
public static int Add(int a, int b)
{
return a + b;
}
public static double PI = 3.1415926;
}
```
静态方法是一种只能通过类名调用的方法,不能通过实例调用。静态方法不能访问实例成员,只能访问静态成员。下面是一个简单的 C# 静态方法示例:
```csharp
public class Calculator
{
public static int Add(int a, int b)
{
return a + b;
}
}
// 调用静态方法
int result = Calculator.Add(1, 2);
```
以上就是 C# 中单例模式和静态类以及静态方法的相关介绍。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)