编辑代码

using System;

public class HelloWorld
{
    // 字段
    class Octopus {
        string name;
        public int Age = 10;

        // 方法与签名
        int Foo (int x) { return x * 2; }
    }

    // 属性
    public class Stock0
    {
        public decimal CurrentPrice       // The public property
        {
            get { return currentPrice; }
            set { currentPrice = value; }
        }
    }

    // 解构器
    class Rectangle
    {
        public readonly float Width, Height;
        public Rectangle (float width, float height)
        {
            Width = width;
            Height = height;
        }

        public void Deconstruct (out float width, out float height)
        {
            width = Width;
            height = Height;
        }
    }

    // 继承
    public class Asset
    {
        public string Name;
        public abstract decimal NetValue { get; }

        // 虚函数
        public virtual decimal Liability => 0;   // Expression-bodied property
    }

    public class Stock : Asset
    {
        public long SharesOwned;
        public decimal CurrentPrice;
        // Override like a virtual method.
         public override decimal NetValue => CurrentPrice * SharesOwned;
    }

    public class House : Asset
    {
        public decimal Mortgage;
        public override decimal Liability => Mortgage;
    }

    // 多态
    public static void Display (Asset asset)
    {
        System.Console.WriteLine (asset.Name);
    }

    // 委托
    delegate int Transformer (int x);
    static int Square (int x) => x * x;

    public static void Main()
    {
        // 调用结构器
        var rect = new Rectangle (3, 4);
        (float width, float height) = rect;            // Deconstruction
        Console.WriteLine (width + " " + height);

        // 继承测试
        Stock msft = new Stock { Name="MSFT",
                                    SharesOwned=1000 };

        Console.WriteLine (msft.Name);           // MSFT
        Console.WriteLine (msft.SharesOwned);    // 1000

        House mansion = new House { Name="Mansion",
                                      Mortgage=250000 };

        Console.WriteLine (mansion.Name);        // Mansion
        Console.WriteLine (mansion.Mortgage);    // 250000

        // 多态测试
        Display(msft)
        Display(mansion)

        // 对象引用转换
        Asset a = msft;                          // Upcast
        Stock s = (Stock)a;                      // Downcast

        // 委托测试
        Transformer t = Square;
        int answer = t(3);     // answer is 9
    }
}