C#: Function in Function possible?

前端 未结 7 975
面向向阳花
面向向阳花 2020-12-05 05:59

Is it possible to declare a method within another method in C#?

For example like that:

void OuterMethod()
{
    int anything = 1;
    InnerMethod();          


        
7条回答
  •  抹茶落季
    2020-12-05 06:55

    UPDATE: C#7 added local functions (https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7#local-functions)

    void OuterMethod()
    {
        int foo = 1;
    
        InnerMethod();
    
        void InnerMethod()
        {
            int bar = 2;
            foo += bar
        }
    
    }
    

    In versions of C# before C#7, you can declare a Func or Action and obtain something similar:

    void OuterMethod()
    {
        int foo = 1;
        Action InnerMethod = () => 
        {
            int bar = 2;
            foo += bar;
        } ;
    
        InnerMethod();
    }
    

提交回复
热议问题