感受 C# 3.0 的優雅

來源:互聯網
上載者:User
問:真的有必要用 C# 3.0 嗎?
答:可以不用,但我們不能忽視它的好處。

-------- 以下是我給的一個例子 --------------------------

只有開始編碼,你才能體會 C# 3.0 的優雅。

對比下面分別用 C# 2.0 和 3.0 寫的同一個類型效果,你感覺到了什嗎?代碼變得更加簡潔,沒有了屬性和其關聯欄位間的重複勞動,也可以少寫幾個 "無聊" 的構造方法。或許很多人對文法簡化持保留意見(包括我本人),但不可否認 3.0 的文法更利於維護,當我們臃腫的的工程代碼從 50000 行縮減到 20000 行時,那麼它所帶來的就不僅僅是少敲鍵盤這麼點好處了。

C# 2.0 class User
{
  private string name;
  private int age;
  private List<string> interest;

  public User()
  {
    interest = new List<string>();
    interest.Add("讀書");
    interest.Add("上網");
  }

  public User(string name, int age) : this()
  {
    this.name = name;
    this.age = age;
  }

  public string Name 
  {
    get { return name; }
    set { name = value; }
  }
  public int Age 
  {
    get { return age; }
    set { age = value; }
  }

  public List<string> Interest 
  {
    get { return interest; }
  }
}

// Invoke
User user = new User("tom", 21);

C# 3.0 class User
{
  public User()
  {
    Interest = new List<string> { "讀書", "上網" };
  }
  
  public string Name { get; set; }
  public int Age { get; set; }
  public List<string> Interest { get; private set; }
}

// Invoke
var user = new User
{
  Name = "tom",
  Age = 21,
};

我的工程中還出現了 CharExtension、StringExtension,甚至是 ObjectExtension 這樣的 Mixin,至於 Lambda、Anonymous types、Linq 自不必多說。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.