编辑代码

using System;
//public class Point { public int X; public int Y; }
//public class Point { public int X, Y; }
public class HelloWorld
{
        // static void Main()
        // {
        //   Point p1 = new Point();
        //   p1.X = 7;

        //   Point p2 = p1;                // Assignment causes copy

        //   Console.WriteLine (p1.X);  // 7
        //   Console.WriteLine (p2.X);  // 7

        //   p1.X = 9;                     // Change p1.X

        //   Console.WriteLine (p1.X);  // 9
        //   Console.Wrusing System;

namespace ClassLearning{
    //字段与属性
    public class Stock
    {
        private decimal currentPrice;     // The private "backing" field

        public decimal CurrentPrice       // The public property
        {
            get { return currentPrice; }
            set { currentPrice = value; }
        }

        //方法与方法签名
        public decimal calculatePrice(decimal increasement) {
            currentPrice += increasement;
            return currentPrice;
        }

        public decimal calculatePrice(int decreasement) {
            currentPrice -= decreasement;
            return currentPrice;
        }

    }

    
    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 Bunny
    {
        public string Name;
        public bool LikesCarrots;
        public bool LikesHumans;

        public Bunny () {}
        public Bunny (string n) { Name = n; }
    }

    //this
    public class Test
    {
        string name;
        public Test (string name) { this.name = name; }
    }


    //静态构造器与静态字段的初始化顺序
    class Foo
    {
        public static Foo Instance = new Foo();
        public static int X = 3;

        static Foo() { Console.WriteLine ($"I'm in static constructor with {X}"); }   
        Foo() { Console.WriteLine ($"I'm in constructor with {X}"); }    // 0

        ~Foo() => Console.WriteLine ("Foo Finalizing");
    }

    //继承
    public class Asset
    {
        public string Name;
        //虚函数
        public virtual decimal Liability => 0;   // Expression-bodied property
    }

    public class Stock1 : Asset   // inherits from Asset
    {
        public long SharesOwned;
    }

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

    //抽象类
    public abstract class AbAsset
    {
        // Note empty implementation
        public abstract decimal NetValue { get; }
    }

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

    // 密封函数
    // public  class SealedStock : AbAsset
    // {
    //     public long SharesOwned;
    //     public decimal CurrentPrice;
    //     // Override like a virtual method.
    //     public override decimal NetValue => CurrentPrice * SharesOwned;
    // }

    // public  class StockInerit : SealedStock
    // {
    //     public long SharesOwned;
    //     public decimal SealedPrice;
    //     // Override like a virtual method.
    //     public override decimal NetValue => SealedPrice * SharesOwned;
    // }
    
    //构造器和继承
    public class BaseClass
    {
        public int X;
        public BaseClass () { }
        public BaseClass (int x) { 
            Console.WriteLine($"BaseClass {X}");
            this.X = x; 
            
        }
    }
    public class SubClass : BaseClass { }

    public class SubClass1 : BaseClass
    {
        public SubClass1 (int x) : base (x) { 
            Console.WriteLine($"SubClass1 {X}");
        }
    }

    //object类型
    public class Stack
    {
        int position;
        object[] data = new object[10];
        public void Push (object obj)   { data[position++] = obj;  }
        public object Pop()               { return data[--position]; }
    }
    

    public class HelloClass
    {
        // Cube是WriteCube的局部方法
        public static void WriteCubes()
        {
            Console.WriteLine (Cube (3));
            Console.WriteLine (Cube (4));
            Console.WriteLine (Cube (5));

            int Cube (int value) => value * value * value;
        }

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

        public static void Main()
        {
            Stock stockA = new Stock();

            stockA.CurrentPrice = 2.0M;

            Console.WriteLine($"The price of stockA is {stockA.CurrentPrice}");

            WriteCubes();

            //解构器
            var rect = new Rectangle (3, 4);
            (float width, float height) = rect;            // Deconstruction
            Console.WriteLine (width + " " + height);      // 3 4

            //对象初始化器
            // Note parameterless constructors can omit empty parentheses
            Bunny b1 = new Bunny { Name="Bo", LikesCarrots=true, LikesHumans=false };
            Console.WriteLine(b1.Name);
            Bunny b2 = new Bunny ("Bob")      { LikesCarrots=true, LikesHumans=false };
            Console.WriteLine(b2.Name);

            Foo test = Foo.Instance;

            Console.WriteLine($"GetType of Foo is {test.GetType()}.");
            Console.WriteLine($"nameof of test is {nameof(test)}.");


            Stock1 msft = new Stock1 { 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);
            
            //对象引用的转换
            Stock1 msft1 = new Stock1();
            Asset asset = msft1;                          // Upcast
            Stock1 stock = (Stock1)asset;                 // Downcast
            Console.WriteLine (stock.SharesOwned);       // <No error>
            Console.WriteLine (stock == asset);              // True
            Console.WriteLine (stock == msft1);           // True

            //as运算符
            Asset a1 = new Asset();
            Stock1 s1 = a1 as Stock1;        // s is null; no exception thrown
            try{
                Stock1 s2 = (Stock1)a1;
            }
            catch(Exception ex) {
               // Console.WriteLine(ex);
            }

            // is运算符
            if (asset is Stock1 s3){
                Console.WriteLine (s3.SharesOwned);
            }

            House mansion1 = new House { Name="McMansion", Mortgage=250000 };
            Asset a2 = mansion1;
            Console.WriteLine (mansion1.Liability);  // 250000
            Console.WriteLine (a2.Liability);          // 250000

            //AbAsset abA = new AbAsset();
            // AbAsset abA = new RealStock {
            //     SharesOwned = 100,
            //     CurrentPrice = 250000
            // };
            // Console.width(abA.NetValue);


            //构造器与顺序
            // s = new Subclass (123);
            SubClass1 sub = new SubClass1 (123);

            //object
            Stack stack = new Stack();
            stack.Push ("sausage");
            string s = (string) stack.Pop();    // Downcast, so explicit cast is needed
            stack.Push (3);
            int three = (int) stack.Pop();

            Console.WriteLine (s);              // sausage
            Console.WriteLine (three);              // 3
                
        }
    }
}
iteLine (p2.X);  // 7
        // }

        //     static void Main()
        // {
        //   Point p1 = new Point();
        //   p1.X = 7;

        //   Point p2 = p1;                // Copies p1 reference

        //   Console.WriteLine (p1.X);  // 7
        //   Console.WriteLine (p2.X);  // 7

        //   p1.X = 9;                     // Change p1.X

        //   Console.WriteLine (p1.X);  // 9
        //   Console.WriteLine (p2.X);  // 9
        // }

        // //数值转换
        // int x = 12345;        // int is a 32-bit integer
        // long y = x;            // Implicit conversion to 64-bit integral type
        // short z = (short)x;  // Explicit conversion to 16-bit integral type
    
        // int i = 1;
        // float f = i;
        // int i2 = (int)f;
        // int i1 = 100000001;
        // float f = i1;            // Magnitude preserved, precision lost
        // int i2 = (int)f;        // 100000000
            
        // //愿意字符串
        // string escaped  = "First Line\r\nSecond Line";
        // string verbatim = @"First Line
        // Second Line";

        // // True if your IDE uses CR-LF line separators:
        // Console.WriteLine (escaped == verbatim);

        // //字符串插值
        // int x = 4;
        // Console.Write ($"A square has {x} sides");// Prints: A square has 4 sides
        
        // string s = $"255 in hex is {byte.MaxValue:X2}";  // X2 = 2-digit Hexadecimal
        // // Evaluates to "255 in hex is FF"

        // int x = 2;
        // string s = $@"this spans {
        // x} lines";


        // //数组
        // //值类型
        // public struct Point { public int X, Y; }
        // ...

        // Point[] a = new Point[1000];
        // int x = a[500].X;                     // 0


        // public class Point { public int X, Y; }
        // ...
        // Point[] a = new Point[1000];
        // int x = a[500].X;              // Runtime error, NullReferenceException


        // Point[] a = new Point[1000];
        // for (int i = 0; i < a.Length; i++) // Iterate i from 0 to 999
        //     a[i] = new Point();       // Set array element i with new point

        // //引用类型元素初始化
        // int[] a = null;


        // //矩形数组
        // int[, ] matrix = new int[3,3];

        // for (int i = 0; i < matrix.GetLength(0); i++)
        //   for (int j = 0; j < matrix.GetLength(1); j++)
        //     matrix[i, j] = i * 3 + j;

        // int[, ] matrix = new int[, ]
        // {
        //   {0,1,2},
        //   {3,4,5},
        //   {6,7,8}
        // };


        // //锯齿形数组
        // int[][] matrix = new int[3][];

        // for (int i = 0; i < matrix.Length; i++)
        // {
        //   matrix[i] = new int[3];                        // Create inner array
        //   for (int j = 0; j < matrix[i].Length; j++)
        //     matrix[i][j] = i * 3 + j;
        // }

        // int[][] matrix = new int[][]
        // {
        //   new int[] {0,1,2},
        //   new int[] {3,4,5},
        //   new int[] {6,7,8,9}
        // };


        //函数参数
        //1.传值
        // class Test
        // {
        //   static void Foo (int p)
        //   {
        //     p = p + 1;                   // Increment p by 1
        //     Console.WriteLine (p);       // Write p to screen
        //   }

        //   static void Main()
        //   {
        //     int x = 8;
        //     Foo (x);                     // Make a copy of x
        //     Console.WriteLine (x);       // x will still be 8
        //   }
        // }

        //2.传引用
        // class Test
        // {
        //   static void Foo (StringBuilder fooSB)
        //   {
        //     fooSB.Append ("test");
        //     fooSB = null;
        //   }

        //   static void Main()
        //   {
        //     StringBuilder sb = new StringBuilder();
        //     Foo (sb);
        //     Console.WriteLine (sb.ToString());     // test
        //   }
        // }

        //3.输出

        // class Test
        // {
        //   static void Swap (ref string a, ref string b)
        //   {
        //     string temp = a;
        //     a = b;
        //     b = temp;
        //   }
        //   static void Main()
        //   {
        //     string x = "Penn";
        //     string y = "Teller";
        //     Swap (ref x, ref y);
        //     Console.WriteLine (x);    // Teller
        //     Console.WriteLine (y);    // Penn
        //   }
        // }

        //可变参数

        // void Foo (int x = 23) { Console.WriteLine (x); }


        // void Foo (int x = 0, int y = 0) { Console.WriteLine (x + ", " + y); }
        // void Test()
        // {
        //   Foo(1);     // 1, 0
        // }

        //null运算符

        //1.null合并运算符
        string s1 = null;
        string s2 = s1 ? ? "nothing";    // s2 evaluates to "nothing"

        //2.null条件运算符
        System.Text.StringBuilder sb = null;
        string s = sb? .ToString();  // No error; s instead evaluates to null

        
        //命名空间
        //处理公钥加密的RSA类型
        System.Security.Cryptography

        //调用了RSA类型的Create方法:
        System.Security.Cryptography.RSA rsa =
            System.Security.Cryptography.RSA.Create();

        //namespace关键字为其中的类型定义了命名空间
        namespace Outer
        {
          namespace Middle
          {
            namespace Inner
            {
              class Class1 {}
              class Class2 {}
            }
          }
        }
     
     
    // 定义委托
    delegate int Transformer (int x);

    static int Square (int x) { 
        int result = x * x;
        Console.WriteLine($"The result of Square is {result}");
        return result; 
    }
    static int Cube (int x) { 
        int result = x * x * x;
        Console.WriteLine($"The result of Cube is {result}");
        return result; 
    }

    public static void Main()
    {
       Transformer t = Square;
       Console.WriteLine($"The result of transformer is {t(3)}");

       t = Cube;
       Console.WriteLine($"The result of transformer is {t(3)}");

       t += Square;
       t(3);

    }
}

using System;

public class PriceChangedEventArgs : EventArgs
{
    public readonly decimal LastPrice;
    public readonly decimal NewPrice;
    public PriceChangedEventArgs (decimal lastPrice, decimal newPrice)
    {
        LastPrice = lastPrice; NewPrice = newPrice;
    }
}

public class Stock
{
    string symbol;
    decimal price;

    public Stock (string symbol) {this.symbol = symbol; }

    public event EventHandler<PriceChangedEventArgs>  PriceChanged;

    protected virtual void OnPriceChanged (PriceChangedEventArgs e)
    {
        PriceChanged? .Invoke (this, e);
    }

    public decimal Price
    {
        get { return price; }
        set
        {
            if (price == value) return;
            decimal oldPrice = price;
            price = value;
            OnPriceChanged (new PriceChangedEventArgs (oldPrice, price));
        }
    }
}

class Test
{
    static void Main()
    {
        Stock stock = new Stock ("THPW");
        stock.Price = 27.10M;
        // Register with the PriceChanged event
        stock.PriceChanged += stock_PriceChanged;
        stock.PriceChanged += stock_20PriceChanged;
        stock.Price = 31.59M;
        stock.Price = 41.59M;
    }

    static void stock_PriceChanged (object sender, PriceChangedEventArgs e)
    {
        if ((e.NewPrice - e.LastPrice) / e.LastPrice > 0.1M)
            Console.WriteLine ("Alert, 10% stock price increase! ");
    }

    static void stock_20PriceChanged (object sender, PriceChangedEventArgs e)
    {
        if ((e.NewPrice - e.LastPrice) / e.LastPrice > 0.2M)
            Console.WriteLine ("Alert, 20% stock price increase! ");
    }
}

using System;


namespace MyStruct
{
    // 结构体
    // 1. 与类类似,但是是值类型,不是引用类型
    // 2. 结构体隐式包含一个无法重写的无参数构造器,将字段按位置为0
    // 3. 定义结构体的构造器时,必须显式为每一个字段赋值
    // 4. 结构体则完全不支持继承
    public struct Point 
    {
        public int X, Y;// 字段: 类或结构体中的变量成员
    }
}

namespace MyClass
{
    // 结构体
    // 1. 与类类似,但是是值类型,不是引用类型
    // 2. 结构体隐式包含一个无法重写的无参数构造器,将字段按位置为0
    // 3. 定义结构体的构造器时,必须显式为每一个字段赋值
    // 4. 结构体则完全不支持继承
    public class Point 
    {
        public int X, Y;// 字段: 类或结构体中的变量成员
    }
}
public class HelloWorld
{
    public static void Main()
    {
        //隐式类型转换和显示类型转换
        int myInteger = 0;
        long myLong = myInteger;
        myInteger = (int)myLong;
       
        //值类型和引用类型
        MyStruct.Point p1 = new MyStruct.Point();
        
        p1.X = 7;
       
        MyStruct.Point p2 = p1;
        
        Console.WriteLine($"p1.X is {p1.X}");
        Console.WriteLine($"p2.X is {p2.X}");

        p1.X = 9;

        Console.WriteLine($"p1.X is {p1.X}");
        Console.WriteLine($"p2.X is {p2.X}");

        MyClass.Point cp1 = new MyClass.Point();
        
        cp1.X = 7;
       
        MyClass.Point cp2 = cp1;
        
        Console.WriteLine($"cp1.X is {cp1.X}");
        Console.WriteLine($"cp2.X is {cp2.X}");

        cp1.X = 9;

        Console.WriteLine($"cp1.X is {cp1.X}");
        Console.WriteLine($"cp2.X is {cp2.X}");
    }
}