AutomaticProperties
该项目演示如何为一个类创建自动化属性,如何使用它们来初始化类的实例。
(1) 创建项目
创建Console Application项目:AutomaticProperties。
(2) 添加资源
添加Class文件:Polygon.cs。
(3) 修改Polygon.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AutomaticProperties
{
class Polygon
{
public int NumSides { get; set; }
public double SideLength { get; set; }
public Polygon()
{
this.NumSides = 4;
this.SideLength = 10.0;
}
}
}
(4) 修改Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace AutomaticProperties
{
class Program
{
static void Entrance()
{
Polygon square = new Polygon();
Polygon triangle = new Polygon { NumSides = 3 };
Polygon pentagon = new Polygon { NumSides = 5, SideLength = 15.5 };
Console.WriteLine("Square: number of sides is {0}, length of each side is {1}",
square.NumSides, square.SideLength);
Console.WriteLine("Triangle: number of sides is {0}, length of each side is {1}",
triangle.NumSides, triangle.SideLength);
Console.WriteLine("Pentagon: number of sides is {0}, length of each side is {1}",
pentagon.NumSides, pentagon.SideLength);
}
static void Main(string[] args)
{
try
{
Entrance();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
(5) 运行测试