嗨(再次提出哲学问题),
有一个私有(private)静态
方法无法访问实例字段,就我的阅读而言,这些方法提供了一点性能改进。
After you mark the methods as static, the compiler will emit non-virtual call sites to these members. Emitting non-virtual call sites will prevent a check at runtime for each call that ensures that the current object pointer is non-null. This can result in a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.
FxCop
那么当我们可以在 private static
方法参数中放置实例字段时,为什么要使用普通的 private
方法呢?这不是效率低下吗?
只是为了形象化我的意思:
public class A
{
private readonly string _key = "ssss";
public bool IsGoodKey()
{
}
private static bool ValidateKeyStatic(string key)
{
return string.IsNullOrEmpty(key);
}
private bool ValidateKey()
{
return string.IsNullOrEmpty(_key);
}
}
现在有两种实现IsGoodKey
的方法:
public bool IsGoodKey()
{
return ValidateKeyStatic(_key);
}
和
public bool IsGoodKey()
{
return ValidateKey();
}
为什么不总是使用私有(private)静态
?
最佳答案
如果性能是静态
的全部目的,那么您当然可以将任何东西设为静态
。但实际上该关键字与性能无关,而是与语义有关 - 即该成员是否属于类(因此所有实例),还是类的特定实例?
假设您要创建类的多个实例。如果每个实例都有一个_key
,那么您肯定需要一个实例字段,而不是静态
字段。另一方面,如果所有实例共享相同的 key ,您当然可以将其设为静态
。
毕竟性能只是关键字的副作用,您不应该永远纯粹基于性能考虑来做出设计决策。
关于c# - 私有(private)静态和私有(private)方法的困境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60928355/