C# rookie tutorial notes

C# rookie tutorial notes

The notes will be continuously updated, please correct me if there are any mistakes, thank you!

1. Basics

0. Input and output

The function Console.ReadLine() is used to receive input from the user and store it in a variable 
Console.WriteLine("Length: {0}", length);//Output 
Console.WriteLine("Hello World") ;//output

1. C# data types

Reference types: Refers to a memory location. 
Object type: When a value type is converted to an object type, it is called boxing; on the other hand, when an object type is converted to a value type, it is called unboxing. 
The object type previously converted from the value type is converted back to the value type

int val= 8;
object obj = val;//先装箱
int nval = (int)obj; //再拆箱

String (String) type: 
C# string Strings can be preceded by @ (called "verbatim strings") to treat escape characters (\) as normal characters, for example:

string str = @"C:\Windows";
//等价于:
string str = "C:\\Windows";

 

2. C# type conversion

• Implicit type conversions - These are C# default conversions that are done in a safe manner and do not result in data loss. For example, converting from a small integer type to a large integer type, from a derived class to a base class.

long lnum = inum;//隐式转换,将int型数据转换为了long型的数据
Class1 c1 = new Class2();//隐式,将一个新建的Class2实例转换为其基类Class1的实例c1

• Explicit casts - ie casts. Explicit conversions require a cast operator, and casting results in data loss.

string locstr = 123.ToString();//整数转字符串
int ii = int.Parse(locstr);// 字符串转整数
Class1 c11 = new Class1();
Class2 c22 = c11 as Class2; //使用as进行显式转换
int ifromd = (int)dnum; //double类型显式转换转为int类型

 

3. C# encapsulation

Encapsulation is implemented using access modifiers

public public access. Not subject to any restrictions. 
private private access. Access is limited to members of this class, and neither subclasses nor instances can access it. 
protected Protected access. Access is limited to this class and subclasses, and instances cannot be accessed. 
internal Internal access. It can only be accessed inside the current project, and it cannot be accessed outside of this project! 
protected internal Internal protected access. It is the combination of protected and internal that can be accessed by combining the current class and subclass of the current project

The modifiable and default modifiers of C# member types are as follows:

member type default modifier can be modified
enum public none
class private public、protected、private、internal、protected internal
interface public none
struct private public、private、internal

Private access modifier 
Only functions within the same class can access its private members. Even an instance of a class cannot access its private members. 
Protected Access Modifier 
The Protected access modifier allows a subclass to access member variables and member functions of its base class. This helps achieve inheritance.

 

4. C# methods

Pass parameters by value 
This is the default way of parameter passing. In this way, when a method is called, a new storage location is created for each value parameter.

Pass parameters by reference (ref is used to declare reference parameters) 
A reference parameter is a reference to the memory location of a variable, and a reference parameter is declared using the ref keyword. 
When parameters are passed by reference, unlike value parameters, it does not create a new storage location for those parameters.

void Start () {
        int a = 100;int b = 200;
        print(a +"\n"+ b);
        Swap(ref a, ref b);
        print(a +"\n"+ b);
    }

    public void Swap(ref int x,ref int y)
    {
        int temp;
        temp = x;x = y;y = temp;
}

按输出传递参数(输出参数out a) 
1. return 只返回一个值, 使用 输出参数 来从函数中返回两个值。 
2. 主方法中不需要赋值,当需要从一个参数没有指定初始值的方法中返回值时,输出参数out特别有用。

    void Start () 
    {
        int a, b;
        ValueTrue(out a, out b);
        Debug.Log(a + "\n" + b);
    }
    private void ValueTrue(out int x,out int y)
    {
        x = 100;y = 200;
    }

也就是,out形参类似于ref形参,但它只能用来将值从方法中传出。在调用之前,并不需要为out形参的变量赋予初始值。在方法中,out形参总是被认为是未赋值的,但在方法结束前必须赋于形参一个值。因此,当调用方法后,out形参引用的变量会包含一个值。

 

5.C# 数组(Array)

foreach 语句用于循环访问集合以获取所需信息,但不应用于更改集合内容以避免产生不可预知的副作用。 
所以,foreach()方法中不能对变量进行赋值,但可以读数组里面的元素来用

 

6.C# 字符串(String)

        string [] ab = { "s", "b" };
        string cd = string.Join(" ", ab);
        print(cd);//输出 s b

 

7.C# 结构(Struct)

结构可定义非默认型构造函数,构造函数和析构函数相反,析构函数专做善后工作 
补:C#接口好比一种模版,这种模版定义了对象必须实现的方法 
结构是值类型数据结构。它使得一个单一变量可以存储各种数据类型的相关数据。struct 关键字用于创建结构。

struct Books
{
   public string title;
};  //C#中struct后面的分号可加可不加,而C++中struct后面的分号必须加。
Books Book1;
Book1.title = "C Programming";

 

8.C# 枚举(Enum)

用enum做Unity中的下拉列表:

    public RotateWays a=RotateWays.rightRotate;
    public enum RotateWays
    {
        leftRotate,
        rightRotate,
        RLBothRotate
    };

 

9.C# 类(Class)

定义了一个类就是定义了一个数据类型 
析构函数用于在结束程序(比如关闭文件、释放内存等)之前释放资源。析构函数不能继承或重载。用法:~Line() //析构函数 
构造函数分为两种

C# 类的静态成员 
直接调用类而不需要创建类的实例来获取。静态变量可在成员函数或类的定义外部进行初始化。您也可以在类的定义内部初始化静态变量 
您也可以把一个成员函数声明为 static。这样的函数只能访问静态变量。静态函数在对象被创建之前就已经存在。

        public static int num;
        public static int getNum()
        {
            return num;
        }

 

10.C# 继承

利于重用代码和节省开发时间,利于维护 
一个类可以派生自多个类或接口,这意味着它可以从多个基类或接口继承数据和函数。 
最多只能继承一个基类或一个接口,也可以同时继承上面两个

接口:

    public interface PaintCost 
   {
      int getCost(int area);

   }

 

基类:

    class Shape 
    {
      public void setWidth(int w)
      {
         width = w;
      }
      public void setHeight(int h)
      {
         height = h;
      }
      protected int width;
      protected int height;
      }

 

子类:

   class Rectangle : Shape, PaintCost
   {
      public int getArea()
      {
         return (width * height);
      }
      public int getCost(int area)
      {
         return area * 70;
      }
   }

 

主动类: 
实例化后,赋值给接口的变量,调用即可

    Rect.setWidth(5);
    Rect.setHeight(7);
    area = Rect.getArea();
    Console.WriteLine("油漆总成本: ${0}" , Rect.getCost(area));

 

11.C# 多态性

静态多态性 
• 函数重载(相同的函数不同功能) 
• 运算符重载(重定义或重载 C# 中内置的运算符)

动态多态性 
动态多态性是通过 抽象类(使用关键字abstract 声明) 和 虚方法(使用关键字 virtual 声明) 实现的

12.C# 接口(Interface)

接口提供了派生类应遵循的标准结构,接口中只用写方法类型和方法名

13.C# 命名空间(Namespace)

1.命名空间的设计目的是提供一种让一组名称与其他名称分隔开的方式。即在一个命名空间中声明的类的名称与另一个命名空间中声明的相同的类的名称不冲突。 
2.using XXX的作用

using UnityEngine.UI;可以不写,如果这样的话:    
UnityEngine.UI.Text text2;
void Start () 
{
        text2.text = "00";
}

 

3.自定义命名空间,命名空间里装的是 类:

namespace first_space
{
   class namespace_cl
   {
      public void func()
      {
         Console.WriteLine("Inside first_space");
      }
   }
}

 

14.C# 正则表达式

用于匹配输入文本

15.C# 异常处理(同Java,了解)

16.C# 文件的输入与输出

二、高级

1.C# 属性

有get;set访问器:获取属性时,会执行get模块。给属性赋值时,会执行set模块。 
若没有写set,也就是说外界是不能修改的。 
访问器(accessor)声明可包含一个 get 访问器、一个 set 访问器,或者同时包含二者。

用法:

      // 声明类型为 string 的 Code 属性
      public string Code
      {
         get
         {
            return code;
         }
         set
         {
            code = value;
         }
      }

 

在一个方法里直接用就好: 
比如:

return "Code = " + Code;//调用get()
s.Code = "001";//实例化后,调用set()

 

2.C# 索引器

让对象以类似数组存取的方式来存取,也就是允许一个对象可以像数组一样被索引。当您为类定义一个索引器时,该类的行为就会像一个 虚拟数组(virtual array) 一样。您可以使用数组访问运算符([ ])来访问该类的实例。

和属性的区别: 
属性返回或设置一个特定的数据成员,而索引器返回或设置对象实例的一个特定值。换句话说,它把实例数据分为更小的部分,并索引每个部分,获取或设置每个部分。 
定义一个属性(property)时包括提供属性名称(public string Code)。索引器定义的时候不带有名称(public string this[int index]),但带有 this 关键字,它指向对象实例。索引器类似于属性,不同之处在于它们的取值函数采用参数。例子:

public class Person 

private string _name = “No one”; 
public Person(string name) 

_name = name; 

//未完 
};

在上面Person类里添加一个索引器:

public string this[string key]  
{  
    get { if (key == "Name")  
            return _name;  
          return null;}  
    set { if (key == "Name")  
            _name = value;  
          return;}  
}  

 

跟属性一样,索引器可以只有set访问器或者get访问器,或者二者都有,不过,索引器可输入参数。

用法:

Person p = new Person ("Arya");  
p ["Name"] = "Anonymous";  
System.Console.WriteLine (p ["Name"]);  

 

3.C# 委托

委托是用于引用与其具有相同标签的方法 
一个对象被一个委托实例化去执行某个方法 
C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。委托(Delegate) 是存有对某个方法的引用的一种引用类型变量。引用可在运行时被改变。 
委托(Delegate)特别用于实现事件和回调方法。换句话说,可以使用委托对象调用可由委托引用的方法。

4.C# 不安全代码

当一个代码块使用 unsafe 修饰符标记时,C# 允许在函数中使用指针变量。不安全代码或非托管代码是指使用了指针变量的代码块。

5.C# 多线程

线程 被定义为程序的执行路径。 
如果您的应用程序涉及到复杂的和耗时的操作,那么设置不同的线程执行路径往往是有益的,每个线程执行特定的工作。

 

 

本文转载自: https://blog.csdn.net/BillCYJ/article/details/79394925

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326027251&siteId=291194637