前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C#4.0新特性 可选命名参数

C#4.0新特性 可选命名参数

作者头像
liulun
发布2022-05-09 11:14:52
3790
发布2022-05-09 11:14:52
举报
文章被收录于专栏:liulun
代码语言:javascript
复制
class Program
    {
        static void PrintStudents(int id = -1, string name = "*", int age = -1)
        {
            Console.WriteLine("the student is id:{0} name:{1} age:{2}", id, name, age);
        }
        static void Main(string[] args)
        {
            PrintStudents(name: "xland", id: 8);
            Console.ReadKey();
        }
    }

如果有方法的多态的话,匹配方式如下

以下函数输出6;也就是执行了第一个方法

代码语言:javascript
复制
static void test3(int x)
        {
            Console.WriteLine(x);
        }
        static void test3(int x, int y = 6)
        {
            Console.WriteLine(x);
            Console.WriteLine(y);
        }
        static void Main(string[] args)
        {
            test3(6);
            Console.ReadKey();
        }

如果有方法的重载的话

如下,输出 8 6 6 

这里与一般的重载有区别  需要注意

代码语言:javascript
复制
public class test4
        {
            public virtual void test5(int a = 6)
            {
                Console.WriteLine(a);
            }
        }
        public class test6 : test4
        {
            public override void test5(int a = 8)
            {
                Console.WriteLine(a);
            }
        }
        static void Main(string[] args)
        {
            test6 a = new test6();
            a.test5();
            test4 b = new test6();
            b.test5();
            test4 c = a as test4;
            c.test5();
            Console.ReadKey();
        }

给方法传递参数的值的时候,可以直接从另一个方法获取值

如下

代码语言:javascript
复制
static void test7(int c,int b)
        {
            Console.WriteLine(b);
        }
        static int test8()
        {
            return 8;
        }
        static void Main(string[] args)
        {
            test7(1,9);
            test7(1,b:test8());
            Console.ReadKey();
        }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2009-10-26,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档