C# 5.0 新特性介绍

2025-10-07 12:03:00

1、创建【控制台应用程序】项目【CSharp.NewFeatures.V50】

C# 5.0 新特性介绍

2、在【Program.cs】中编辑测试代码整体结构如下

C# 5.0 新特性介绍

3、测试辅助类【CSharpV50】的代码如下:

1)方法 AwaitFunctionAsync:用于测试异步特性

       /// <summary>

        /// 使用 async 实现异步方法

        /// </summary>

        public async void AwaitFunctionAsync()

        {

            Console.WriteLine("进入async方法 " + DateTime.Now.ToString());

            await Task.Delay(1000);

            Console.WriteLine("结束async方法 " + DateTime.Now.ToString());

        }

C# 5.0 新特性介绍

4、测试辅助类【CSharpV50】的代码如下:

2)方法 InsertLog :记录调用此方法的信息

       

/// <summary>

        ///  记录调用此方法的信息

        /// </summary>

        /// <param name="memberName">调用此方法的方法或者属性名</param>

        /// <param name="sourceFilePath">调用此方法的所在物理路径</param>

        /// <param name="sourceLineNumber">调用此方法的所在行数</param>

        public void InsertLog([CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0)

        {

            Console.WriteLine("memberName = {0}, sourceFilePath = {1},sourceLineNumber = {2},at {3}", memberName, sourceFilePath, sourceLineNumber, DateTime.Now);

        }

C# 5.0 新特性介绍

5、Main方法的整体测试结构如下:

记得需要在Main方法内部结尾处添加代码:Console.ReadLine(); 用于停住命令行显示界面,看测试结果,否则,看不到结果

C# 5.0 新特性介绍

6、Main方法内部的 Async Feature 测试代码如下:

 #region 1、Async Feature

            Console.WriteLine("============= 【Async Feature】 Start ===========");

            // 调用异步方法,由于异步方法内部有等待1秒钟,因此, 【Async Feature】 End 输出后,仍然会输出异步方法内部的信息

            // 如果不是异步方法,则会输出完方法内部信息,之后再输出 【Async Feature】 End

            sharpV50.AwaitFunctionAsync();

            Console.WriteLine("============= 【Async Feature】 End ===========");

            Console.WriteLine();

            Console.WriteLine();

            #endregion

C# 5.0 新特性介绍

7、Main方法内部的 Caller Information 测试代码如下:

// 1)CallerFilePathAttribute:编译期的调用方的路径(注意是编译期的物理路径,不管放到哪里运行,都是编译期的路径)

// 2)CallerLineNumberAttribute:方法调用处的行号(即下面例子 sharpV50.InsertLog(); 在当前文件中的行号 )

// 3)CallerMemberNameAttribute:调用方的方法或者属性(即此处的main方法名)

 #region 2、Caller Information

            Console.WriteLine("============= 【Caller Information】 Start ===========");

            // 1)CallerFilePathAttribute:编译期的调用方的路径(注意是编译期的物理路径,不管放到哪里运行,都是编译期的路径)

            // 2)CallerLineNumberAttribute:方法调用处的行号(即下面例子 sharpV50.InsertLog(); 在当前文件中的行号 )

            // 3)CallerMemberNameAttribute:调用方的方法或者属性(即此处的main方法名)

            // 4)上述标记是修饰方法的参数的

            sharpV50.InsertLog();

            Console.WriteLine("============= 【Caller Information】 End ===========");

            Console.WriteLine();

            Console.WriteLine();

            #endregion

C# 5.0 新特性介绍

8、运行结果如下

C# 5.0 新特性介绍

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢