声明接口在语法上与声明抽象类完全相同,但不允许提供接口中任何成员的实现方式。 一般情况下,接口只能包含方法、属性、索引器和事件的声明。不能实例化接口 ,它只能包含其成员的 签名。接口既不能有构造函数,接口定义也不允许包含运算符重载。

6.1 定义和实现接口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 定义接口
{
    public interface IBankAccount
    {
        void PayIn(decimal amount);
        bool Withdraw(decimal amount);
        decimal Balance
        { get; }



    }

    class Program
    {
        static void Main(string[] args)
        {
            IBankAccount x = new SaveAccount();
            IBankAccount y = new SaveAccount();
            x.PayIn(200);
            x.Withdraw(100);
            Console.WriteLine(x.ToString());
            y.PayIn(500);
            y.Withdraw(600);
            y.Withdraw(100);
            Console.WriteLine(y.ToString());

        }
    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 定义接口
{
    public class SaveAccount : IBankAccount
    {
        private decimal balance;
        public void PayIn(decimal amount)
        {
             balance+= amount;
        }
        public bool Withdraw(decimal amount)
        {
            if (balance >= amount)
            {
                balance -= amount;
                return true;

            }
            else
            {
                Console.WriteLine("Withdraw1 attempt failed");
                return false;
            }

        }
        public decimal Balance
        {
            get
            {
                return balance;

            }
        }
        public override string ToString()
        {
            return String.Format("Venus Bank Saver:Balance={0,6:C}", balance);
        }


    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 定义接口
{
    public class GoldAccount : IBankAccount
    {
        private decimal balance;
        public void PayIn(decimal amount)
        {
            balance += amount;
        }
        public bool Withdraw(decimal amount)
        {
            if (balance >= amount)
            {
                balance -= amount;
                return true;

            }
            else
            {
                Console.WriteLine("Withdraw1 attempt failed");
                return false;
            }

        }
        public decimal Balance
        {
            get
            {
                return balance;

            }
        }
        public override string ToString()
        {
            return String.Format("Venus Bank Saver:Balance={0,6:C}", balance);
        }


    }
}
6.接口

转载于:https://www.cnblogs.com/sharp-c/archive/2012/09/09/2678099.html

相关文章:

  • 2022-01-09
  • 2021-11-16
  • 2021-11-29
  • 2021-10-01
  • 2022-02-23
  • 2022-01-31
  • 2021-08-20
  • 2021-11-24
猜你喜欢
  • 2022-02-14
  • 2021-11-17
  • 2021-08-27
  • 2022-12-23
  • 2022-01-07
  • 2021-11-20
相关资源
相似解决方案