C#:函数中的函数可能吗?

发布于 2024-11-05 01:15:43 字数 221 浏览 0 评论 0原文

C# 中是否可以在另一个方法中声明一个方法?

例如这样:

void OuterMethod()
{
    int anything = 1;
    InnerMethod();     // call function
    void InnerMethod()
    {
        int PlitschPlatsch = 2;
    }
}

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

For example like that:

void OuterMethod()
{
    int anything = 1;
    InnerMethod();     // call function
    void InnerMethod()
    {
        int PlitschPlatsch = 2;
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

风月客 2024-11-12 01:15:43

更新:添加的本地函数 C# 版本 7。

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();
}

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();
}
伴随着你 2024-11-12 01:15:43

更新:C#7 添加了本地函数 (https: //learn.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# 版本中,您可以声明 FuncAction 并获得类似的内容:

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

    InnerMethod();
}

UPDATE: C#7 added local functions (https://learn.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();
}
眼泪也成诗 2024-11-12 01:15:43

是的,有办法。使用 C# 3.0,您可以使用 Func类型这。

例如,我昨天写了这个:

  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);

目的是为现有图像添加水印。我想让水印文本的大小约为图像宽度的 85%。但我想倾斜水印文本,使其以一定角度书写。这表明需要根据角度进行一些三角计算,我想要一个小函数来执行这项工作。 Func 非常适合这一点。

上面的代码定义了一个 Func (一个函数),它接受 SizeF 并返回一个 double,用于文本的实际宽度。以给定角度绘制。这个Func是函数内的一个变量,并且该变量本身保存一个(对函数的引用)。然后我可以在我定义的范围内调用该“私有”函数。 Func 可以访问在其执行范围内之前定义的其他变量。因此,可以在 angleWidth() 函数中访问 angle 变量。


如果您想要返回 void 的可调用逻辑,可以使用 Action< T>,同理。 .NET 定义了接受 N 个参数的 Func 泛型,因此您可以使它们变得非常复杂。 Func 就像返回非 void 的 VB 函数或 C# 方法; Action 就像 VB Sub 或返回 void 的 C# 方法。

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.

把回忆走一遍 2024-11-12 01:15:43

自从提出这个问题以来已经过去了五年,现在 C# 7 即将到来。

它预计将包括本地功能,并且显然已经实现。

本地函数(提案:#259)[当前在未来分支中]

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

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

卷耳 2024-11-12 01:15:43

delegate 关键字就是这样做的。

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

    int anything = 1;
    InnerMethod();
}

不要忘记,根据作用域,PlitschPlatsch 变量将无法在 InnerMethod 外部访问。

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.

思念绕指尖 2024-11-12 01:15:43

如果您主要希望“隐藏”一个只是“帮助程序”的方法...另一种选择是使您的帮助程序私有。这样它们就不会成为类公共接口的一部分。

这样做的优点是,如果需要,可以重复使用助手;但它/它们不会是调用方法的“内部”。

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.

遗失的美好 2024-11-12 01:15:43

查看匿名方法。我想这就是你要找的。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文