随笔 - 58  文章 - 1  评论 - 2  阅读 - 38646 

 

一、字符串插值

复制代码
 class Program
    {
        static void Main(string[] args)
        {
            //c#6.0新特性:字符串插值
            var name = "Jack";
            Console.WriteLine($"Hello {name}");//结果为:Hello Jack

            Person p = new Person() { FirstName = "Jack", LastName = "Wang", Age = 68 };
            //以下结果等价于:var results = string.Format("First Name: {0} LastName: {1} Age: { 2} ", p.FirstName, p.LastName, p.Age);
            var result = $"First Name:{p.FirstName} Last Name:{p.LastName}  Age:{p.Age}";

            //字符串插值不光是可以插简单的字符串,还可以直接插入代码
            Console.WriteLine($"Jack is saying {Program.SayHello()}");//结果为:Jack is saying Hello
            var info = $"Your discount is {await GetDiscount()}";
            ReadLine();
        }

        public static string SayHello()
        {
            return "Hello";
        }
    }
复制代码

二、空操作符 ( ?. )

 ?. 操作符,当一个对象或者属性职为空时直接返回null, 就不再继续执行后面的代码

if (user != null && user.Project != null && user.Project.Tasks != null && user.Project.Tasks.Count > 0)
 {
   Console.WriteLine(user.Project.Tasks.First().Name);
 }

现在我们可以不用写 IF 直接写成如下这样:

Console.WriteLine(user?.Project?.Tasks?.First()?.Name);

这个?. 特性不光是可以用于取值,也可以用于方法调用

复制代码
 class Program
{
    static void Main(string[] args)
    {
        User user = null;
        user?.SayHello();
        Console.Read();
    }
}

public class User
{
    public void SayHello()
    {
        Console.WriteLine("Ha Ha");
    }
}
复制代码

 还可以用于数组的索引器

复制代码
class Program
{
    static void Main(string[] args)
    {
        User[] users = null;

        List<User> listUsers = null;

        // Console.WriteLine(users[1]?.Name); // 报错
        // Console.WriteLine(listUsers[1]?.Name); //报错

        Console.WriteLine(users?[1].Name); // 正常
        Console.WriteLine(listUsers?[1].Name); // 正常

        Console.ReadLine();
    }
}
复制代码

注意: 上面的代码虽然可以让我们少些很多代码,而且也减少了空异常,但是我们却需要小心使用,因为有的时候我们确实是需要抛出空异常,那么使用这个特性反而隐藏了Bug

三、 NameOf

过去,我们有很多的地方需要些硬字符串,比如

复制代码
if (role == "admin")
{
}

public string Name
{
  get { return name; }
  set
  {
      name= value;
      RaisePropertyChanged("Name");
  }
}
复制代码

现在有了C#6 NameOf后,我们可以这样

复制代码
public string Name
{
  get { return name; }
  set
  {
      name= value;
      RaisePropertyChanged(NameOf(Name));
  }
}

  static void Main(string[] args)
    {
        Console.WriteLine(nameof(User.Name)); //  output: Name
        Console.WriteLine(nameof(System.Linq)); // output: Linq
        Console.WriteLine(nameof(List<User>)); // output: List
        Console.ReadLine();
    }
复制代码

注意: NameOf只会返回Member的字符串,如果前面有对象或者命名空间,NameOf只会返回 . 的最后一部分, 另外NameOf有很多情况是不支持的,比如方法,关键字,对象的实例以及字符串和表达式

四、在Catch和Finally里使用Await

之前的版本里,C#开发团队认为在Catch和Finally里使用Await是不可能,而现在他们在C#6里实现了它

复制代码
        Resource res = null;
        try
        {
            res = await Resource.OpenAsync(); // You could always do this.  
        }
        catch (ResourceException e)
        {
            await Resource.LogAsync(res, e); // Now you can do this … 
        } 
        finally
        {
            if (res != null) await res.CloseAsync(); // … and this.
        }
复制代码

五、表达式方法体

一句话的方法体可以直接写成箭头函数,而不再需要大括号

复制代码
 public class Programe1
    {
        public static string SayHello() => "Hello world";

        public static string JackSayHello() => $"Jack {SayHello()}";

        static void Main()
        {
            Console.WriteLine(SayHello());
            Console.WriteLine(JackSayHello());
            Console.Read();
        }
    }
复制代码

六、属性初始化器

之前我们需要赋初始化值,一般是在构造函数赋值,现在可以这样

public class Person
{
    public int Age { get; set; } = 100;
}

七、异常过滤器 Exception Filter

复制代码
          try
            {
                throw new ArgumentException("Age");
            }
            catch(ArgumentException a) when (a.Message.Equals("Age"))
            {
                throw new ArgumentException("Name Exception");
            }
            catch(ArgumentException arg) when(arg.Message.Equals("Age"))
            {
                throw new ArgumentException("not handle");
            }
            catch (Exception e)
            {
                throw e;
            }        
复制代码

之前,一种异常只能被Catch一次,现在有了Filter后可以对相同的异常进行过滤

八、 Index 初始化器

这个主要是用在Dictionary上

复制代码
var names = new Dictionary<int, string>
            {
                [0] = "jack",
                [1] = "Kimi",
                [2] = "Jason",
                [3] = "Lucy"
            }
foreach (var item in names)
     {
           Console.WriteLine($"{item.Key}={item.Value}");
     }     
复制代码

九、using 静态类的方法可以使用 using static 

复制代码
namespace ConsoleTest
{
    using static System.Console;
    public class Programe1
    {
        static void Main()
        {
            WriteLine("Hello world");
            ReadLine();
        }
    }
}
复制代码

作者: 王德水
出处:http://www.cnblogs.com/cnblogsfans/p/5086292.html
版权:本文版权归作者所有,转载需经作者同意。

 

posted on   花开花落-2014  阅读(1355)  评论(1编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示