gpt4 book ai didi

c# - 私有(private)方法与本地函数

转载 作者:行者123 更新时间:2023-12-03 13:45:43 24 4
gpt4 key购买 nike

据我了解,本地函数和私有(private)方法都只是作为实现细节——公共(public)方法的助手。为什么我要选择一个而不是另一个?

当使用私有(private)方法时,我在对象和方法之间创建了一种语义关系(虽然从外部看不到),这并不总是合理的。这就是为什么我的第一直觉是本地函数是要走的路,除非有多个公共(public)方法使用它,在这种情况下我会使用私有(private)方法。

但是有没有目标支持其中之一的理由?有没有一种情况比另一种更可取?使用其中任何一个的优点和缺点是什么?

最佳答案

这都是关于代码可读性的。看着motivation局部函数

Local functions make the intent of your code clear. Anyone reading your code can see that the method is not callable except by the containing method. For team projects, they also make it impossible for another developer to mistakenly call the method directly from elsewhere in the class or struct.



局部函数的主要原因是给出意图:此代码仅用于此方法;不要从其他地方重复使用它。另有说明:私有(private)方法表明它们可能从其他类方法中重用。

如 Roslyn-Rep here 中所述,此语言功能背后还有更多用例。 .:

  • It is very common to write a helper method that is only used from one place, but it makes the code less clear to the reader because the association between the helper function and the thing it is helping is not explicit. Local functions makes the association part of the syntax.
  • An iterator method that validates its arguments (write a non-iterator function to validate the arguments, and then return the result of invoking a local iterator function)
  • A Task-returning method that has no async machinery in the common case where it doesn't need to "go async"
  • You are writing a method that returns an array, but want the syntactic convenience of the iterator method syntax (yield return).


博客文章 https://devblogs.microsoft.com/premier-developer/dissecting-the-local-functions-in-c-7/ 中解释了这些用例。

关于c# - 私有(private)方法与本地函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60137882/

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