编写代码(两种方式实现)
第二种方式是采用表达式主体定义属性来实现对字段的操作(注意:从C#7开始,才可以将这些属性作为表达式主体成员来实现,即在get关键字或set关键字的后面使用=>符号指定读或写操作的表达式,这样就组成了表达式主体定义)
由于本人使用的软件为VS2010所以C#版本比较低,并不能采用表达式主体定义属性来实现对字段的操作(C# 版本和.NET 版本以及VS版本的对应关系请看链接 )
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace a
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Circle c = new Circle();
c.R =Convert .ToDouble( textBox1.Text);
label2.Text = string.Format("半径为:{0}的圆,面积为:{1}",c.R,c.Area);
}
}
/*第二种方式
public class Circle
{
const double pi = 3.1415926;
private double r;
public double R
{
get => r;
set => r=(value<0)?0:value;
}
public double Area=>pi*R*R;
}*/
//第一种方式
public class Circle
{
const double pi = 3.1415926;
private double r;
public double R
{
get
{
return r;
}
set
{
if (value < 0)
{
r = 0;
}
else
{
r = value;
}
}
}
public double Area
{
get
{
return (pi*R*R);
}
}
}
}
运行结果: