在对类的不同成员进行访问与操作时,我们所选用的方法会有不同的方法。取值/赋值方法,是沿袭下来的方法,就OO里,也是一样可以正常使用。但是为了使类的使用者,既方便使用,又能更好的隐藏私有成员,Property是一个不错的选择,这是一种优雅的方法。其实,在NET世界中,所有数据都是以property呈现的。
当然,property也不是万能的,对于静态成员的访问,它就会失效了。
例举:
使用取值/赋值方法
|
使用property方法
|
using System; using System.Collections.Generic; using System.Text;
namespace ConsoleApplication1 {
public class Account { private static double interestrate;
public static void SetInterestRate double amt) { interestrate = amt; }
public static double GetInterestRate() { return interestrate; } }
class Program { static void Main(string[] args) { Account.SetInterestRate(5.5); double i =Account .GetInterestRate(); double p = Account.GetInterestRate(); Console.WriteLine("The first number is {0} and the Second number is {1}",i,p);
Console.ReadKey(); } } }
|
using System; using System.Collections.Generic; using System.Text;
namespace ConsoleApplication1 { public class Account { private double interestrate; public double interestRate { get { return interestrate; } set { interestrate = value; } } }
class Program { static void Main(string[] args) { Account a1 = new Account(); double i = 5.5; a1.interestRate = i; WriteLine(a1.interestRate); Account a2 = new Account(); Console.WriteLine(a2.interestRate);
Console.ReadKey(); } } }
|
结果和注释
|
|
5.5
0
|
5.5
5.5
|
Type text here