C# 可选参数 命名参数

1.可选参数

        可选参数是.NET4中新添加的功能,应用可选参数的方法在被调用的时可以选择性的添加需要的参数,而不需要的参数由参数默认值取代。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Program
    {
        /// <summary>
        /// 可选参数  命名参数
        /// </summary>
        static void Main(string[] args)
        {
            Console.WriteLine(ShowComputer());
            Console.WriteLine(ShowComputer("P5300","1G"));
            Console.Read();
        }
  
        private static string ShowComputer(string cpu = "i3 370M", string ram = "4G", string disk = "320G")
        {
            return "My computer ... \nCpu:" + cpu + "\nRam:" + ram + "\nDisk:" + disk + "\n";
        }
    }

  

代码运行的结果图下图:

2.命名参数

          命名参数是把参数附上参数名称,这样在调用方法的时候不必按照原来的参数顺序填写参数,只需要对应好参数的名称也能完成方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Program
    {
        /// <summary>
        /// 可选参数  命名参数
        /// </summary>
        static void Main(string[] args)
        {
            Console.WriteLine(ShowComputer("i3 370M","2G","320G"));
            Console.WriteLine(ShowComputer(disk: "320G", cpu: "i3 370M", ram: "2G"));
            Console.Read();
        }
  
        private static string ShowComputer(string cpu, string ram, string disk)
        {
            return "My computer ... \nCpu:" + cpu + "\nRam:" + ram + "\nDisk:" + disk + "\n";
        }
    }

    命名参数如果只是改变参数的顺序,这样的意义并不大,我们没有必要为了改变顺序而去用命名参数,他与可选参数结合才能显示出他真正的意义。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Program
    {
        /// <summary>
        /// 可选参数  命名参数
        /// </summary>
        static void Main(string[] args)
        {
            Console.WriteLine(ShowComputer(ram: "3G"));
            Console.Read();
        }
  
        private static string ShowComputer(string cpu = "i3 370M", string ram = "2G", string disk = "320G")
        {
            return "My computer ... \nCpu:" + cpu + "\nRam:" + ram + "\nDisk:" + disk + "\n";
        }
    }

  程序只赋值了第二个参数ram,其他参数均为默认值,运行结果大家应该都知道了。这样命名参数和可选参数都发挥了他们独特的作用。

 

posted @   每天进步多一点  阅读(594)  评论(0编辑  收藏  举报
编辑推荐:
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求
· 2 本地部署DeepSeek模型构建本地知识库+联网搜索详细步骤
点击右上角即可分享
微信分享提示