属性的定义:其实属性是字段和方法的一个交集---看起来像是一个字段,行为上又像一个方法。一个属性可以包含两个代码块,分别为get和set关键字开头,其实,get块包含的事在读取属性时要执行的语句(取值代码);set块包含的是向属性写入时要执行的语句(赋值语句)。
为结构或者类声明一个可读/可写的属性:
struct ScreenPosition
{
...
public int X
{
get { ... }
set { ... }
}
...
}
为结构或者类声明一个只读的属性:
struct ScreenPosition{
...
public int X
{
get { ... }
}
...
}
为结构或者类声明一个只写的属性:
struct ScreenPostion{
...
public int Y
{
set{ ...}
}
...
}
在接口中声明一个属性:
interface IScreenPosition
{
int X { get; set; } // no body
int Y { get; set; } // no body
}
在结构或者类中实现一个接口属性:
struct ScreenPosition : IScreenPosition
{
public int X
{
get { ... }
set { ... }
}
public int Y
{
get { ... }
set { ... }
}
}
附上Visual C# 2010上的一个例子:
using System;
using System.Collections.Generic;
using System.Text;
namespace AutomaticProperties
{
class Program
{
static void DoWork()
{
// to do
Polygon square = new Polygon();
Polygon triangle = new Polygon { NumSides = 3 };
Polygon pentagon = new Polygon { NumSides = 5, SideLength = 15.5 };
Console.WriteLine("Square:number of side is {0},length of each side is {1}",square.NumSides,square.SideLength);
Console.WriteLine("Triangle:number of side is {0},length of each side is {1}", triangle.NumSides, triangle.SideLength);
Console.WriteLine("Pentagon:number of side is {0},length of each side is {1}", pentagon.NumSides, pentagon.SideLength);
}
static void Main(string[] args)
{
try
{
DoWork();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}