为什么这两个要一起讲,因为这两个常常一起出现,可选参数常常用来替代以前的方法重载,可选参数一般置于普通参数的后面,但是当多个可选参数同时出现的时候,而你又想启用可选参数的优点,又不想每个可选参数都传递实参,这个时候编译器不知道你想给那个参数传递参数,就需要指定传递那个参数的名字,这个就是命名参数的由来,我是按照自己的理解来讲的,不是书面化的语言。
下面举个例子就明白了
[C#] 纯文本查看 复制代码 private RectangleFigure CreateFigure(Color color, PointF pointF = new PointF(), SizeF sizeF = new SizeF(),int priority = basicPriority)
{
color = Color.FromArgb(alpha, color.R, color.G, color.B);
RectangleFigure figure;
if (pointF.IsEmpty || sizeF.IsEmpty)
{
float w = Math.Min(canvas.ClientRectangleWorld.Width, backDie.Width) / 10;
float h = Math.Min(canvas.ClientRectangleWorld.Height, backDie.Height) / 10;
float x = (canvas.ClientRectangleWorld.Left + canvas.ClientRectangleWorld.Right - w) / 2;
float y = (canvas.ClientRectangleWorld.Top + canvas.ClientRectangleWorld.Bottom - h) / 2;
figure = new RectangleFigure(new RectangleF(x, y, w, h));
}
else
{
figure = new RectangleFigure(new RectangleF(pointF, sizeF));
}
figure.nLayer = priority;
} SyntaxHighlighter Copyright 2004-2013 Alex Gorbatchev.
这里只想传递Priority 参数,其它的可选参数用默认值,那么就必须要用命名参数,告诉编译器我传递的是哪一个可选参数
[C#] 纯文本查看 复制代码 editingRectangle = CreateFigure(color,priority:priority); SyntaxHighlighter Copyright 2004-2013 Alex Gorbatchev. |