C# 3.0 - 新功能 - Automatic properties
C# 3.0 又新增許多令人激賞的功能,今天先看一下 Automatic properties
大家先想一下之前要宣告一個 property 要如何做?就像下方的程式碼:
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
在 C# 3.0 的寫法可以直接寫為:
public string Name { get; set; }
是不是又加簡潔了!
完整的範例如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NewLanguageFeatures
{
public class Customer
{
public int CustomerId { get; private set; }
public string Name { get; set; }
public string City { get; set; }
public Customer(int Id)
{
CustomerId = Id;
}
public override string ToString()
{
return Name + "\t" + City + "\t" + CustomerId;
}
}
class Program
{
static void Main(string[] args)
{
Customer c = new Customer(1);
c.Name = "台灣微軟";
c.City = "台北市";
Console.WriteLine(c);
}
}
}
筆者使用的環境:Windows 2008 RC0 English + Visual Studio 2008
Comments
- Anonymous
December 03, 2007
PingBack from http://www.absolutely-people-search.info/?p=2702