c# - 私有(private)静态和私有(private)方法的困境

标签 c#

嗨(再次提出哲学问题),

有一个私有(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/

相关文章:

c# - 将标准输出重定向到列表<string>或流

C# ListView.Columns.Add 的参数

C# 结构的自动深拷贝

c# - Silverlight 5 通过 ssl 连接到 WCF 服务

c# - 为什么 MessageBox 不是 TopMost?

c# - 是否可以减小来自字节数组的图像的大小

c# - 如何强制 C# 构建过程包含代码中未使用的程序集

具有可选参数的 C# 递归函数

c# - 我可以在用于 SQLite 的类中使用字符串列表吗?

c# - 在 Click 事件中从 TextBox 中选择文本