C#深入学习(1)

c#也用了好久了,最近重新看书,看到一些之前没怎么注意过的或者没怎么用过的语法特性,记录一下,争取以后多用用。

Implicitly Typed Local Variables

C#中也有类型推断的功能,关键字为var

var x = "hello";
var y = new System.Text.StringBuilder();
var z = (float)Math.PI;
等价于
string x = "hello";
System.Text.StringBuilder y = new System.Text.StringBuilder();
float z = (float)Math.PI;

当然,不实际声明变量类型并不代表类型就是动态的,类型还是静态的,以下代码会报错

var x = 5;
x = "hello"; // 报错; x 是Int类型

Null-Coalescing Operator

??操作符的意思是如果非null,则返回左边,如果左边为null,则返回右边,虽然用if else也能完成,但是这种常见的任务,c#专门提供了这个操作符,使用之后就可以使代码更加简洁
用法如下

string s1 = null;
string s2 = s1 ?? "abc"; // s2最后为"abc"

Null-conditional operator (C# 6)

?.操作符的意思是如果左边不为null,则调用右边的方法,用法如下

System.Text.StringBuilder sb = null;
string s = sb?.ToString(); // 不会报错,因为sb为null,所以不会调用方法
和下面代码等价
string s = (sb == null ? null : sb.ToString());

using static (C# 6)

静态导入,和java的静态导入一样(不知道为啥c#要到6.0才支持…)
导入静态方法,静态变量

using static System.Console;
class Test
{
static void Main() { WriteLine ("Hello"); }
}

Aliasing Types and Namespaces

给命名空间取一个别名,防止冲突

using PropertyInfo2 = System.Reflection.PropertyInfo;
class Program { PropertyInfo2 p; }
//
using R = System.Reflection;
class Program { R.PropertyInfo p; }

Object Initializers

public class Bunny
{
public string Name;
public bool LikesCarrots;
public bool LikesHumans;
public Bunny () {}
public Bunny (string n) { Name = n; }
}
//通过使用object initializers,你可以这样初始化对象,在调用构造器的同时给实例变量赋值
Bunny b1 = new Bunny { Name="Bo", LikesCarrots=true, LikesHumans=false };
Bunny b2 = new Bunny ("Bo") { LikesCarrots=true, LikesHumans=false };
//等价于
Bunny temp1 = new Bunny(); 
temp1.Name = "Bo";
temp1.LikesCarrots = true;
temp1.LikesHumans = false;
Bunny b1 = temp1;   
Bunny temp2 = new Bunny ("Bo");
temp2.LikesCarrots = true;
temp2.LikesHumans = false;
Bunny b2 = temp2;

Implementing an indexer

class Sentence
{
string[] words = "The quick brown fox".Split();
public string this [int wordNum] // indexer
{
get { return words [wordNum]; }
set { words [wordNum] = value; }
}
}
//使用
Sentence s = new Sentence();
Console.WriteLine (s[3]); // fox
s[3] = "kangaroo";
Console.WriteLine (s[3]);

你可能感兴趣的:(c#)