gpt4 book ai didi

c# - 使无状态方法静态化是好事还是坏事?

转载 作者:太空狗 更新时间:2023-10-29 23:12:50 26 4
gpt4 key购买 nike

如果类方法不依赖于类的状态,那么它可以是静态的。在这种情况下,将此类方法设为静态是好的还是坏的做法?

(标记为 C#,但可能适用于方法必须是类成员的许多 OO 语言。)

最佳答案

Visual Studio Code Analysis 和 ReSharper 建议将这些方法设为静态,因为这会带来微小的性能优势:

来自 documentation :

Members that do not access instance data or call instance methods can be marked as static (Shared in Visual Basic). After you mark the methods as static, the compiler will emit nonvirtual call sites to these members. Emitting nonvirtual call sites will prevent a check at runtime for each call that makes sure that the current object pointer is non-null. This can achieve a measurable performance gain for performance-sensitive code. In some cases, the failure to access the current object instance represents a correctness issue.

对于非“性能敏感”代码,这是一个品味问题。如果我没有充分的理由不这样做,我个人会遵守 ReSharper 的建议。

关于c# - 使无状态方法静态化是好事还是坏事?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41488027/

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