C#: Function in Function possible?

前端 未结 7 949
面向向阳花
面向向阳花 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:45

    The delegate keyword does just that.

    void OuterMethod()
    {
        var InnerMethod = delegate()
        {
            int PlitschPlatsch = 2;
        };
    
        int anything = 1;
        InnerMethod();
    }
    

    Don't forget that, per scoping, the PlitschPlatsch variable won't be accessible outside InnerMethod.

    0 讨论(0)
  • 2020-12-05 06:47

    Update: Local functions where added in version 7 C#.

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

    In previous version C# you have to use action like this:

    void OuterMethod()
    {
        int anything = 1;
        Action InnedMethod = () =>
        {
            int PlitschPlatsch = 2;
        };
        InnedMethod();
    }
    
    0 讨论(0)
  • 2020-12-05 06:51

    If you're looking mainly to "hide" a method that is just a "helper" ... another option is to make your helper(s) private. That way they don't become part of your class's public interface.

    This has the advantage that the helper(s) can be reused if necessary; but it / they won't be "internal" to the calling method.

    0 讨论(0)
  • 2020-12-05 06:51

    Take a look at anonymous methods. I think that's what you're looking for.

    0 讨论(0)
  • 2020-12-05 06:52

    yes, there are ways. With C# 3.0 you have the Func<T> type that does this.

    For example, I wrote this yesterday:

      var image = Image.FromFile(_file);
      int height = image.Height;
      int width = image.Width;
      double tan = height*1.00/width;
      double angle = (180.0 * Math.Atan(tan) / Math.PI);
      var bitmap = new System.Drawing.Bitmap(image, width, height);
      var g = System.Drawing.Graphics.FromImage(bitmap);
      int fontsize = 26; // starting guess
      Font font = null;
      System.Drawing.SizeF size;
    
      Func<SizeF,double> angledWidth = new Func<SizeF,double>( (x) =>
          {
              double z = x.Height * Math.Sin(angle) +
              x.Width * Math.Cos(angle);
              return z;
          });
    
      // enlarge for width
      do
      {
          fontsize+=2;
          if (font != null) font.Dispose();
          font = new Font("Arial", fontsize, System.Drawing.FontStyle.Bold);
          size = g.MeasureString(_text, font);
      }
      while (angledWidth(size)/0.85 < width);
    

    The purpose was to add a watermark to an existing image. I wanted to make the size of the watermark text about 85% of the width of the image. But I wanted to cant the watermark text so that it was written on an angle. This revealed the need to do some trig calculations based on the angles, and I wanted a little function to perform that work. The Func is perfect for that.

    The code above defines a Func (a function) that accepts a SizeF and returns a double, for the actual width of the text when it is drawn at the given angle. This Func is a variable within a function, and the variable itself holds a (reference to a) function. I can then invoke that "private" function within the scope where I've defined it. The Func has access to the other variables that are defined before it, in its execution scope. So, the angle variable is accessible within the angledWidth() function.


    If you want invokable logic that returns void, you can use Action<T>, in the same way. .NET defines Func generics that accept N arguments, so you can make them pretty complicated. A Func is like a VB Function or a C# method that returns non-void; an Action is like a VB Sub, or a C# method that returns void.

    0 讨论(0)
  • 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();
    }
    
    0 讨论(0)
提交回复
热议问题