UltraDebug

 找回密码
 立即注册

QQ登录

只需一步,快速开始

搜索
热搜: A C D R G Y M Z X S P
公益项目,接受捐赠
查看: 2349|回复: 0
收起左侧

[C#] C# 命名参数和可选参数

[复制链接]
Honeys

主题

0

回帖

UD

新手上路

UID
42
积分
34
注册时间
2022-5-15
最后登录
1970-1-1
2022-7-30 23:01:09 | 显示全部楼层 |阅读模式
为什么这两个要一起讲,因为这两个常常一起出现,可选参数常常用来替代以前的方法重载,可选参数一般置于普通参数的后面,但是当多个可选参数同时出现的时候,而你又想启用可选参数的优点,又不想每个可选参数都传递实参,这个时候编译器不知道你想给那个参数传递参数,就需要指定传递那个参数的名字,这个就是命名参数的由来,我是按照自己的理解来讲的,不是书面化的语言。
下面举个例子就明白了
[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.
UltraDebug免责声明
✅以上内容均来自网友转发或原创,如存在侵权请发送到站方邮件9003554@qq.com处理。
✅The above content is forwarded or original by netizens. If there is infringement, please send the email to the destination 9003554@qq.com handle.
回复 打印

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|Archiver|站点地图|UltraDebug ( 滇ICP备2022002049号-2 滇公网安备 53032102000034号)

GMT+8, 2025-6-20 16:11 , Processed in 0.027374 second(s), 8 queries , Redis On.

Powered by Discuz X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表