gpt4 book ai didi

c# - 使用静态方法还是实例化类?

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

最近,我对在数百个线程使用的类中使用静态方法存在争议。
在我看来,“第一”解决方案没有特殊的好处,除了它更易于为类(class)的客户使用,但我被告知这是一个非常糟糕的主意,我必须使用“第二”解决方案。谁能给我清楚的解释为什么我错了?
非常感谢!

聚苯乙烯
我们假设字典是线程安全的。

class A
{
static Dictionary<int, string> m_dic = new Dictionary<int, string>();
public static string GetData1(int nKey)
{
return m_dic[nKey];
}
public string GetData2(int nKey)
{
return m_dic[nKey];
}
}

//these func are called from threads...
void ThreadFunc1()
{
print A.GetData1(1);
}

void ThreadFunc2()
{
A a = new A();
print a.GetData2(1);
}

问候,
列昂尼德

最佳答案

使用实例成员暗示着(至少对我而言),与实例本身有关—它的状态,或者可能是它的行为(被覆盖的方法而言)(即“状态”是实例的执行时间类型) 。

在这种情况下,这些都不是正确的-因此,我将创建实例视为不良样式,从而导致误导代码。

关于c# - 使用静态方法还是实例化类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3351697/

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