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

复制代码
Code
    class Program
    {
        
static void PrintStudents(int id = -1string 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;也就是执行了第一个方法

复制代码
Code
        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 

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

复制代码
Code
        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();
        }
复制代码

 

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

如下

复制代码
Code
        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();
        }
复制代码
posted @   liulun  阅读(433)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示