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]);

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
  © 2014-2022 ITdaan.com