syntax of c#

C# is a strongly typed, object-oriented programming language widely used in the .NET framework and the Unity game engine. Here is an overview of some basic C# syntax:

  1. Variables and data types : C# supports many basic data types, such as int (integer), float (floating point), double (double precision floating point), char (character), and string (string). You can declare and initialize a variable, for example:int myNumber = 5;

  2. Operators : C# provides various operators to manipulate data, such as + (addition), - (subtraction), * (multiplication), / (division) and % (remainder). These operators can be used in arithmetic expressions, for example:int result = 5 * 6;

  3. Conditional statement : C# supports if-else and switch-case structures, which are used to execute different code blocks based on certain conditions. For example:

int x = 10;
if (x > 5)
{
    
    
    Console.WriteLine("x is greater than 5");
}
else
{
    
    
    Console.WriteLine("x is less than or equal to 5");
}
  1. Loops : C# supports for, while, and do-while loop structures for performing repetitive tasks. For example:
for (int i = 0; i < 10; i++)
{
    
    
    Console.WriteLine(i);
}
  1. Array : An array is a data structure used to store a collection of elements of the same type. For example:int[] myArray = new int[5];

  2. Function : A function is an organized, reusable piece of code that performs a single or related task. A function definition includes the function name, return type, parameters, etc. For example:

public int AddNumbers(int a, int b)
{
    
    
    return a + b;
}
  1. Object-oriented programming : C# supports object-oriented programming, including concepts such as class (class), object (object), inheritance (inheritance), encapsulation (encapsulation) and polymorphism (polymorphism).

The above are just some basic grammars of C#. C# also has many advanced features and functions, such as interfaces, delegates, events, LINQ, etc. If you need a more detailed tutorial or have other questions, please feel free to ask.

encapsulation

Encapsulation is a core concept in object-oriented programming and one of the three major features of object-oriented programming (the other two are inheritance and polymorphism).

The basic idea of ​​encapsulation is to wrap the state (properties) and behaviors (methods) of an object together to form a single entity or unit, and hide its internal implementation details from the outside. The main purpose of this is to protect the integrity of the data and to control access to that data.

As an example, suppose we have a class representing a bank account. This class might have properties such as account balance, and methods such as deposit and withdrawal. We want to not allow direct external modification of account balances, but only through deposit and withdrawal methods. In this way, we can ensure that only legal operations can affect the account balance and avoid unreasonable situations such as the balance becoming negative.

In C#, we usually achieve encapsulation by using access modifiers (such as public, private, protected, etc.). For example, we can declare a class property as private so that it can only be accessed inside the class, and then provide public methods (getter and setter) to control the reading and writing of this property.

The following is an example of a simple C# wrapper:

public class BankAccount
{
    
    
    private double balance;  // private属性,外部无法直接访问

    // 提供一个public方法来获取余额
    public double GetBalance()
    {
    
    
        return balance;
    }

    // 提供一个public方法来存款
    public void Deposit(double amount)
    {
    
    
        if (amount > 0)
        {
    
    
            balance += amount;
        }
    }

    // 提供一个public方法来取款
    public void Withdraw(double amount)
    {
    
    
        if (amount > 0 && balance >= amount)
        {
    
    
            balance -= amount;
        }
    }
}

In this way, users of the BankAccount class can only change the balance through the Deposit and Withdraw methods, and cannot directly modify the value of the balance.

What is polymorphism?

Polymorphism (Polymorphism) is another important concept in object-oriented programming, and it is also one of the three major characteristics of object-oriented programming (the other two are inheritance and encapsulation).

In programming languages, the concept of polymorphism means that an object can have multiple forms. The most common polymorphism is reflected in the reference of the parent class or interface to the object of the subclass, and then the specific method to be called is determined at runtime. This way, the same interface can have different behaviors, providing code flexibility.

There are two main forms of polymorphism:

  1. Compile-time polymorphism (also known as static polymorphism or method overloading): This is determined at compile time. Since multiple methods with the same name but different parameter lists can be created, the compiler can Its argument list determines which method to call.

  2. Runtime polymorphism (also known as dynamic polymorphism or method overriding): At runtime, a virtual function or overridden method determines which method to call.

Here is a simple example of polymorphism in C#:

public class Animal  // 基类
{
    
    
    public virtual void MakeSound()
    {
    
    
        Console.WriteLine("The animal makes sound");
    }
}

public class Dog : Animal  // Dog 类继承自 Animal 类
{
    
    
    public override void MakeSound()  // 重写 MakeSound 方法
    {
    
    
        Console.WriteLine("The dog barks");
    }
}

public class Cat : Animal  // Cat 类继承自 Animal 类
{
    
    
    public override void MakeSound()  // 重写 MakeSound 方法
    {
    
    
        Console.WriteLine("The cat meows");
    }
}

// 程序使用
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();

myAnimal.MakeSound();  // 输出 "The animal makes sound"
myDog.MakeSound();     // 输出 "The dog barks"
myCat.MakeSound();     // 输出 "The cat meows"

In this example, MakeSoundthe method Animalis declared in the class as virtual, which means it can be overridden in derived classes. Then in the Dogand Catclass, we overrideoverride MakeSoundthe method using the keyword. In this way, when we call myDog.MakeSound()and myCat.MakeSound(), the corresponding rewritten version of the method will be called, realizing polymorphism.

Introducing interfaces, delegates, events, LINQ

  1. Interfaces : Interfaces in C# define a protocol or behavior that a class or structure can follow. Interfaces cannot contain definitions of fields, operators, and declarations of nested types. Also, members of an interface cannot be static. An interface can inherit from one or more other interfaces.

    Example:

    public interface IAnimal
    {
          
          
        void Eat();
    }
    
    public class Dog : IAnimal
    {
          
          
        public void Eat()
        {
          
          
            Console.WriteLine("Dog is eating.");
        }
    }
    
  2. Delegate (Delegates) : In C# programming, a delegate (Delegate) is a reference type that can be used to encapsulate a method with a specific method signature and return type. You can think of a delegate as a reference to a method, which allows you to pass the method as a parameter, or store the method in a data structure. This feature allows you to write more flexible and dynamic code.

Delegates are useful in many situations, such as event handling and asynchronous calls. When you create a delegate, you are actually defining a type of method that can be called. You can then create a delegate instance that references a method that conforms to that type.

Here is an example of a basic delegate usage:

// 定义一个委托,该委托表示一个没有返回值、接受一个string参数的方法
public delegate void ShowMessage(string message);

// 一个符合委托定义的方法
public void SayHello(string name)
{
    
    
    Console.WriteLine($"Hello, {
      
      name}!");
}

// 使用委托
ShowMessage showMessageDelegate = SayHello;
showMessageDelegate("Alice");  // 输出 "Hello, Alice!"

In this example, ShowMessageit is a delegate type, which represents a method that does not return a value and accepts a string parameter. SayHellois a method that conforms to the definition of this delegate. Then we create a ShowMessagedelegate instance of the type showMessageDelegateand let it refer to SayHellothe method. Finally, we showMessageDelegateactually call SayHellothe method by calling the delegate instance.

  1. Events (Events) : In C#, an event (Event) is a special member that a class or object can provide. Events are represented by variables of type Delegate, which is essentially a publish-subscribe model. When an event occurs (published), all methods (subscribers) that subscribe to the event will be executed automatically.

In C#, the definition of an event usually includes three parts:

  1. Delegate type definition : Define the signature (parameter and return type) of the method associated with the event.

  2. Event definition : Use special eventkeywords to define events.

  3. Event triggering : Triggering an event under a certain condition causes all methods that subscribe to the event to be executed.

Here is a simple event usage example:

// 1. 委托类型的定义
public delegate void MyEventHandler();

// 2. 事件的定义
public class MyClass
{
    
    
    public event MyEventHandler MyEvent;

    public void TriggerEvent()
    {
    
    
        MyEvent?.Invoke();
    }
}

// 在其他地方使用
public class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        MyClass myObject = new MyClass();

        // 订阅事件
        myObject.MyEvent += () =>
        {
    
    
            Console.WriteLine("Event triggered!");
        };

        // 触发事件
        myObject.TriggerEvent();  // 输出 "Event triggered!"
    }
}

In this example, we first define a MyEventHandlerdelegate type called that represents a method with no parameters and no return value. Then in MyClassthe class we define an MyEventevent called with type MyEventHandler. We then provide a TriggerEventmethod, which fires MyEventthe event. In Mainthe method, we create an MyClassinstance myObjectof and subscribe to its MyEventevent. When we call myObject.TriggerEvent(), all MyEventmethods subscribed to the event will be executed, thus outputting "Event triggered!".

  1. LINQ (Language Integrated Query) : LINQ is a query syntax in C# that allows you to retrieve and process data using SQL-like queries. This can include arrays, enums, XML, databases, etc.

    Example:

    List<int> numbers = new List<int> {
          
           1, 2, 3, 4, 5 };
    
    var evenNumbers = from num in numbers
                      where num % 2 == 0
                      select num;
    
    foreach(var num in evenNumbers)
    {
          
          
        Console.WriteLine(num); // 输出 2 和 4
    }
    

The above is only a basic overview and simple examples of each concept. In actual use, interfaces, delegates, events, LINQ, etc. have more features and usages. Which feature to use depends on your actual needs and problem scenarios.

Guess you like

Origin blog.csdn.net/m0_57236802/article/details/131658752