取值/赋值方法与Property方法

在对类的不同成员进行访问与操作时,我们所选用的方法会有不同的方法。取值/赋值方法,是沿袭下来的方法,就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
posted on 2006-09-14 11:41 Rex.Sun 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/Rex2006/archive/2006/09/14/504039.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值