C#基本语法

发布时间 2023-10-10 21:27:19作者: newbieking

基本语法

// See https://aka.ms/new-console-template for more information
// Hello World Console.WriteLine("Hello, World!"); // declare variable int x = 0; // expression x = x + 1; x = 0; // function calling logStringNTimes(x.ToString(), x); // function defining void logStringNTimes(string str, int times) { // choice structure if (times <= 0) { return; } switch (times) { case <= 0: return; default: break; } // sequential structure times++; // looping structure for (int i = 0; i < times; i++) { Console.WriteLine(str); } int times_tmp = times; while (times_tmp > 0) { Console.WriteLine(times_tmp--); } } // instantiate a class Parent parent = new Parent; parent.Name = "dad"; parent.Age = 18; // actual 19 (calling property setter)

 Parent Class defination

// object orientation
class Parent
{
    // field
    private string name;

    // property 
    public string Name { get => name; set => name = value; }
    public int Age 
    { 
        get => {
            ++age;
        }
        set => {
            age = ++value;
        }
    }

    private int age;

    // method
    public string selfIntro()
    {
        return $"name: {name}; age: {age}";
    }

    // class method 
    public static string theClassName() 
    {
        return typeof(Parent).Name;
    }
}