作为一个简单的例子,假设我有一个如下所示的 C# 单例类:
using System.Collections.Generic;
public sealed class RestrictedNameCollection : List<string>
{
private static object _lock = new object();
private RestrictedNameCollection()
{
}
private static RestrictedNameCollection _instance;
public static RestrictedNameCollection Instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
if (_instance == null)
{
var nameList = new List<string>();
nameList.Add("Jack");
nameList.Add("Jill");
nameList.Add("John");
nameList.Add("Jane");
var restrictedNameCollection = new RestrictedNameCollection();
foreach (var name in nameList)
{
restrictedNameCollection.Add(name);
}
_instance = restrictedNameCollection;
}
}
}
return _instance;
}
}
}
我可以通过以下两种方式将 IsRestrictedName(string name)
方法添加到类中。
public bool IsRestrictedName(string name)
{
return Contains(name);
}
或者:
public static bool IsRestrictedName(string name)
{
return Instance.Contains(name);
}
我可以通过调用 RestrictedNameCollection.Instance.IsRestrictedName("Jack")
使用第一个版本。但我更喜欢能够调用第二个版本 RestrictedNameCollection.IsRestrictedName("Jack")
因为它很简洁。
我的问题是,是否有任何理由让我应该远离该方法的静态版本?这纯粹是句法辩论吗?或者是否存在我应该关注的潜在性能影响?
最佳答案
内存问题有点棘手,但基本上一旦调用一次,所有数据(“jack”等)都会加载到内存中并一直保留到 dll 卸载。在性能方面,我更担心线程安全。然而.. 就我想说的而言.. 为什么你要付出所有这些努力来填充一个列表?只需创建几个静态函数,如“populatenames”和“populaterestricted”?
我觉得你想多了....
关于c# - C# .NET Singleton 类中的静态方法是否会对性能或内存消耗产生负面影响?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40874691/