C#:study(4)--属性
@属性
属性的格式通常如下:
type name
{
get {...}
set {...}
}
理解属性不定义存放位置这一点很重要。所以,属性控制对域的访问,而它本身并不提供这个域。域必须被定义为独立于属性之外。属性也可以定义为只读或只写形的。
@通过属性访问基类的私有变量
属性的格式通常如下:
type name
{
get {...}
set {...}
}
理解属性不定义存放位置这一点很重要。所以,属性控制对域的访问,而它本身并不提供这个域。域必须被定义为独立于属性之外。属性也可以定义为只读或只写形的。
1
using System;
2
class SimpProp
3
{
4
int prop;//由myprop控制的域
5
public SimpProp()
6
{
7
prop = 0
8
}
9
public int myprop//myprop属性
10
{
11
get
12
{
13
return prop;
14
}
15
set
16
{
17
if(value >= 0) prop = value;
18
}
19
}
20
}
21
22
class PropertyDemo
23
{
24
public static void Main()
25
{
26
SimProp ob = new SimProp();
27
Console.WriteLine("Original value of ob.myprop: " + ob.myprop);
28
ob.myprop = 100;
29
Console.WriteLine("Value of ob.myprop: " + ob.myprop);
30
}
31
}
using System;2
class SimpProp3
{4
int prop;//由myprop控制的域5
public SimpProp()6
{7
prop = 08
}9
public int myprop//myprop属性10
{11
get12
{13
return prop;14
}15
set16
{17
if(value >= 0) prop = value;18
}19
}20
}21

22
class PropertyDemo23
{24
public static void Main()25
{26
SimProp ob = new SimProp();27
Console.WriteLine("Original value of ob.myprop: " + ob.myprop);28
ob.myprop = 100;29
Console.WriteLine("Value of ob.myprop: " + ob.myprop);30
}31
}@通过属性访问基类的私有变量
1
using System;
2
//二维对象类
3
class TwoDShape
4
{
5
double pri_width;
6
double pri_height;
7
public double width
8
{
9
get {return pri_width;}
10
set {pri_width = value;}
11
}
12
public double height
13
{
14
get {return pri_height;}
15
set {pri_height = value;}
16
}
17
public void showDim()
18
{
19
Console.WriteLine("Width and height are " +width + " and " + height);
20
}
21
}
22
//TwoDShape的派生类,表示三角形
23
class Triangle : TwoDShape
24
{
25
public string style;
26
public double area()
27
{
28
return wedth + height / 2;//通过属性访问
29
}
30
public void showStyle()
31
{
32
Console.WriteLine("Triangle is " + style);
33
}
34
}
using System;2
//二维对象类3
class TwoDShape4
{5
double pri_width;6
double pri_height;7
public double width8
{9
get {return pri_width;}10
set {pri_width = value;}11
}12
public double height13
{14
get {return pri_height;}15
set {pri_height = value;}16
}17
public void showDim()18
{19
Console.WriteLine("Width and height are " +width + " and " + height);20
}21
}22
//TwoDShape的派生类,表示三角形23
class Triangle : TwoDShape24
{25
public string style;26
public double area()27
{28
return wedth + height / 2;//通过属性访问29
}30
public void showStyle()31
{32
Console.WriteLine("Triangle is " + style);33
}34
}




浙公网安备 33010602011771号