developer tip

C # : Function in Function 가능?

copycodes 2020. 11. 27. 08:21
반응형

C # : Function in Function 가능?


C #의 다른 메서드 내에서 메서드를 선언 할 수 있습니까?

예를 들면 다음과 같습니다.

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

업데이트 : 버전 7 C #에 추가 된 로컬 기능 .

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

이전 버전 C #에서는 다음과 같은 작업을 사용해야합니다.

void OuterMethod()
{
    int anything = 1;
    Action InnedMethod = () =>
    {
        int PlitschPlatsch = 2;
    };
    InnedMethod();
}

업데이트 : C # 7 추가 로컬 함수 ( 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
    }

}

C # 7 이전의 C # 버전에서는 Funcor를 선언하고 Action비슷한 것을 얻을 수 있습니다 .

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

    InnerMethod();
}

예, 방법이 있습니다. C # 3.0 Func<T>에서는이를 수행 하는 유형이 있습니다.

예를 들어 어제 이렇게 썼습니다.

  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.


Five years have passed since this question was asked and now C# 7 is coming.

It's slated to include local functions, and is apparently already implemented.

Local functions (Proposal: #259) [currently in future branch]

https://github.com/dotnet/roslyn/issues/259


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.


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.


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

참고URL : https://stackoverflow.com/questions/5884319/c-function-in-function-possible

반응형