类的属性与字段:
-
当字段为private时。可以通过属性来访问私有字段,也可以在类的内部用方法来访问字段。
-
可以在属性中将set访问器或者get访问器设为private,实现只写或只读。
-
与字段不同,属性是一个函数成员。
example
using System;
namespace classTest012
{
class constructor
{
static void Main(string[] args)
{
Person2 per = new Person2();
per.SetName("xiao hong"); //通过方法给字段赋值。
per.Age = 23;//通过属性给字段赋值。
per.Print();
Person person = new Person();
person.Name = "lily";
person.Age = -1;//通过属性赋值。
person.Print();
Console.Read();
}
}
class Person
{
private string _name;
private int _age;
public string Name
{
get
{
return _name;
}
set
{
this._name = value;
}
}
public int Age
{
private
get
{
return _age;
}
set
{
if ((value > 0) && (value < 130))
{
_age = value;
}
else
{
Console.WriteLine("无效的年龄!!!");
}
}
}
public void Print()
{
Console.WriteLine("name: {0},age:{1}", _name, _age);
}
}
class Person2
{
private string _name;
//定义GetName方法
public string GetName()
{
return _name;
}
//定义SetName方法,显示定义 value 参数
public void SetName(string value)
{
this._name = value;
}
private int _age;
public int Age //属性
{
private get
{
return _age;
}
set
{
if ((value < 0) || (value > 130))
Console.WriteLine("输入的年龄值无效!!");
else
{
this._age = value;
}
}
}
public void Print()
{
Console.WriteLine("name: {0},age= {1}", _name, _age);
}
}
class C1
{
private int realValue;
private int complexValue;
public int RealValue
{
get //只读
{
return realValue;
}
}
public int ComplexValue
{
set //只写
{
complexValue = value;
}
}
}
/// <summary>
/// 自动实现属性:c# 允许只声明属性而不声明后备字段,编译器会创建隐藏的后备字段。并且自动挂接到get,set访问器上。
/// </summary>
class C2
{
public int RealValue //分配内存
{
get;
set;
}
}
class Triangle
{
public double A = 3;
public double B = 5;
public double GetThird
{
get
{
return Math.Sqrt((A * A) + (B * B));
}
}
}
}