我经常遇到私有方法,这些方法变得非常大并且包含重复的任务,但是这些任务非常具体,因此将它们提供给任何其他代码部分是没有意义的.
因此,在这种情况下能够创建"内部方法"真的很棒.
是否有任何技术(甚至是哲学?)限制阻止C#给我们这个?还是我错过了什么?
2016年更新:即将到来,它被称为"本地功能".见标记答案.
Meh*_*ari 14
好吧,我们可以在函数内部定义"匿名方法"(我不建议使用它们来组织一个大方法):
void test() {
Action t = () => Console.WriteLine("hello world"); // C# 3.0+
// Action t = delegate { Console.WriteLine("hello world"); }; // C# 2.0+
t();
}
Run Code Online (Sandbox Code Playgroud)
看来我们将通过C# 7 / Visual Studio 15中的本地函数得到我想要的东西:https://github.com/dotnet/roslyn/issues/2930
private int SomeMethodExposedToObjectMembers(int input)
{
int InnerMethod(bool b)
{
// TODO: Change return based on parameter b
return 0;
}
var calculation = 0;
// TODO: Some calculations based on input, store result in calculation
if (calculation > 0) return InnerMethod(true);
return InnerMethod(false);
}
Run Code Online (Sandbox Code Playgroud)
太糟糕了,我为此等了 7 年多:-)
另请参阅早期版本的 C# 的其他答案。
| 归档时间: |
|
| 查看次数: |
1634 次 |
| 最近记录: |