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 特性,其他的还有,可以自己去研究一下。