C#3.0新特性的介紹(自動屬性)
萬丈高樓平地起,基礎是重中之重。
所有我一定要搞點基礎的東西,雖然已經(jīng)是搞了幾年程序了,有些基礎知識也懂,但是沒有系統(tǒng)的掌握。
而且發(fā)現(xiàn)現(xiàn)在弄的B/S系統(tǒng)里很多技術真的很落后了,也許我現(xiàn)在學的新技術有些用不上,并不代表不要學,
所有現(xiàn)在開始更加要全部重新學習或者復習一些基礎東西。
C# 3.0新特性之自動屬性(Auto-Implemented Properties)
類的定義
- public class Point
- {
- private int x;
- private int y;
- public int X { get { return x; } set { x = value; } }
- public int Y { get { return y; } set { y = value; } }
- }
與下面這樣定義等價,這就是c#3.0新特性
- public class Point
- {
- public int X {get; set;}
- public int Y {get; set;}
- }
- 一個例子源碼
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace NewLanguageFeatures1
- {
- public class Customer
- {
- public int CustomerId { get; private set; }
- public string Name { get; set; }
- public string City { get; set; }
- public override string ToString()
- {
- return Name + “\t” + City + “\t” + CustomerId;
- }
- }
- class Program
- {
- static void Main(string[] args)
- {
- Customer c = new Customer();
- c.Name = “Alex Roland”;
- c.City = “Berlin”;
- c.CustomerId = 1;
- Console.WriteLine(c);
- }
- }
- }
錯誤 1 由于 set 訪問器不可訪問,因此不能在此上下文中使用屬性或索引器“NewLanguageFeatures1.Customer.CustomerId” D:\net\NewLanguageFeatures\NewLanguageFeatures1\Program.cs 41 13 NewLanguageFeatures1
Program output showing the result of calling ToString on the Customer class after adding a new CustomerId property
正確的例子源碼:
- 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 = “Alex Roland”;
- c.City = “Berlin”;
- Console.WriteLine(c);
- }
- }
- }
關于C#3.0新特性的自動屬性功能就討論到這里,希望對大家有用。
【編輯推薦】