2015年11月15日 星期日

C11_2 介面作為回傳值的例子

using System;
namespace C11_2
{
    public interface IShape
    {
        int Area
        {
            get;
            set;
        }
        void Caculate();
    }
    public class Square : IShape
    {
        int b = 0;
        #region IShape 成員
        public int Area
        {
            get
            {
                return b * b;
            }
            set
            {
                b = value;
            }
        }
        public void Caculate()
        {
            Console.WriteLine("開始計算面積....");
        }
        #endregion
    }
    public class MyClass
    {
        public MyClass(IShape shape)
        {
            shape.Caculate();
            Console.WriteLine("正方形的面積為:{0}",shape.Area);
        }
        public IShape MyOutput(IShape shape)
        {
            //shape.Area = 100; //也可以在這裡修改正方形的邊長
            return shape;
        }
    }
    public class Test
    {
        public static void Main()
        {
            Console.WriteLine("請輸入正方形邊長:");
            //建立Square類別變數square,並使用其作為參數建立MyClass 形變數myClass
            Square square = new Square();
            square.Area = Convert.ToInt32(Console.ReadLine());
            MyClass myClass = new MyClass(square);
            //獲取回傳值,並輸出其面積Area屬性
            Square square2 = (Square)myClass.MyOutput(square);
            Console.WriteLine("獲取回傳值,輸出面積Area為:{0}",square2.Area);
        }
    }
}

沒有留言: