Jar*_*Par 56
更新:在版本7 C#中添加的本地函数.
void OuterMethod()
{
int foo = 1;
InnerMethod();
void InnerMethod()
{
int bar = 2;
foo += bar
}
}
Run Code Online (Sandbox Code Playgroud)
在以前的C#版本中,您必须使用以下操作:
void OuterMethod()
{
int anything = 1;
Action InnedMethod = () =>
{
int PlitschPlatsch = 2;
};
InnedMethod();
}
Run Code Online (Sandbox Code Playgroud)
jer*_*enh 41
更新: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
}
}
Run Code Online (Sandbox Code Playgroud)
在C#7之前的C#版本中,您可以声明一个Func
或者Action
获得类似的东西:
void OuterMethod()
{
int foo = 1;
Action InnerMethod = () =>
{
int bar = 2;
foo += bar;
} ;
InnerMethod();
}
Run Code Online (Sandbox Code Playgroud)
Che*_*eso 16
是的,有方法.使用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);
Run Code Online (Sandbox Code Playgroud)
目的是为现有图像添加水印.我想让水印文字的大小约为图像宽度的85%.但是我想要去掉水印文本以便它以一定的角度写出来.这表明需要根据角度进行一些触发计算,我想要一点功能来完成这项工作.这Func
是完美的.
上面的代码定义了一个Func
(一个函数),它接受a SizeF
并返回a double
,用于在给定角度绘制文本时的实际文本宽度.这Func
是函数中的变量,变量本身包含(引用a)函数.然后我可以在我定义它的范围内调用"私有"函数.Func可以在其执行范围内访问在其之前定义的其他变量.因此,angle
变量可在angledWidth()
函数内访问.
如果您想要返回的可调用逻辑void
,您可以Action<T>
以相同的方式使用..NET定义了接受N个参数的Func泛型,因此可以使它们变得非常复杂.Func类似于VB函数或返回非void的C#方法; Action就像VB Sub,或返回void的C#方法.
自提出这个问题已经过去了五年,现在C#7即将到来.
它将包含本地功能,并且显然已经实现.
本地功能(提案:#259)[目前在未来的分支机构]
https://github.com/dotnet/roslyn/issues/259