gpt4 book ai didi

c# 用于存储的单独类

转载 作者:太空宇宙 更新时间:2023-11-03 18:49:34 25 4
gpt4 key购买 nike

我使用了多个类,我需要一个...假设所有类和方法的全局存储。创建用于存储的静态类是否正确?

public static class Storage
{
public static string filePath { get; set; }
}

或者还有其他方法吗?

最佳答案

如果您真的需要让您的示例成为单例,那么您可以按照以下方式进行操作。

public class StorageSingleton
{
private static readonly StorageSingleton instance;

static StorageSingleton() {
instance = new Singleton();
}
// Mark constructor as private as no one can create it but itself.
private StorageSingleton()
{
// For constructing
}

// The only way to access the created instance.
public static StorageSingleton Instance
{
get
{
return instance;
}
}

// Note that this will be null when the instance if not set to
// something in the constructor.
public string FilePath { get; set; }
}

调用和设置单例的方法如下:

// Is this is the first time you call "Instance" then it will create itself
var storage = StorageSingleton.Instance;

if (storage.FilePath == null)
{
storage.FilePath = "myfile.txt";
}

或者,您可以将以下内容添加到构造函数中以避免空引用异常:

// Mark constructor as private as no one can create it but itself.
private StorageSingleton()
{
FilePath = string.Empty;
}

警告语;从长远来看,制作任何全局或单例都会破坏您的代码。稍后您真的应该检查存储库模式。

关于c# 用于存储的单独类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1276292/

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