C# 6.0 新特性

Unity设置使用.net 4.6(Unity2018.2.2)

c# 6.0是.net 4.6的一部分,unity默认使用的是.net 3.5,可以在Edit – Project Settings – Player中,将Scripting Runtime Version修改为Experimental (.Net 4.6 Equivalent),然后重启即可。

 

c# 6.0 新特性

pubic class Test: MonoBehaviour{

     public int testValue => testRandomValue;
     private int testRandomValue;

 
     void Start()
    {
         testRandomValue = Random.Range(1, 10);
        print(testRandomValue+":"+testValue);

        TestList tl = new TestList() ;
        string results = $"name: {tl?.name} height: {tl?.height} status: {tl?.status}";
        print(results);
        TestList t2 = new TestList { name = "B", height = 170, status = 1 };
        string results2 = $"name: {t2?.name} height: {t2?.height} status: {t2?.status}";
        print(results2);
    }

}

public class TestList {

    public string name { get; set; } = "A";
    public float height { get; set; } = 180;
    public int status { get; set; } = 0;

    public string SayHello()
    {
        return "hello";
        
    }
}

 解析:

1.表达式方法体

public int testValue => testRandomValue;

还可以跟方法

private static string SayHello() => "Hello World";

private static string TomSayHello() => $"Tom {SayHello()}";

 

2.自动属性初始化器

 public string name { get; set; } = "A";

可以不用在构造函数里初始化

 

3.空操作符 ( ?. )

tl?.name  

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

?. 特性不光是可以用于取值,也可以用于方法调用,如果对象为空将不进行任何操作,下面的代码不会报错,也不会有任何输出。

4.字符串插值

 string results = $"name: {tl?.name} height: {tl?.height} status: {tl?.status}";

类似string.Format()

字符串插值不光是可以插简单的字符串,还可以直接插入代码

 string results = $"name:{tl.name} sayhello {tl.SayHello()}"

5.空合并运算符(??)

A??B

当A为null时返回B,A不为null时返回A本身

空合并运算符为右结合运算符,即操作时从右向左进行组合的。如,“A??B??C”的形式按“A??(B??C)”计算

 

 

以上是比较常见的C# 6.0 特性,其他的还有,可以自己去研究一下。

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值