万丈高楼平地起,基础是重中之重。
所有我一定要搞点基础的东西,虽然已经是搞了几年程序了,有些基础知识也懂,但是没有系统的掌握。
而且发现现在弄的B/S系统里很多技术真的很落后了,也许我现在学的新技术有些用不上,并不代表不要学,
所有现在开始更加要全部重新学习或者复习一些基础东西。
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新特性的自动属性功能就讨论到这里,希望对大家有用。
【编辑推荐】