快速入门C#编程之struct和class对比 -电脑资料

电脑资料 时间:2019-01-01 我要投稿
【www.unjs.com - 电脑资料】

   

    1、下面是一个结构的定义:

    ?

    1

    2

    3

    4

    5

    public struct Point

    {

    public int X { get; set; }

    public int Y { get; set; }

    }

    什么时候用结构:

用于小型的数据结构其中的值一般不修改

    2、类的定义:

    ?

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    public class Animal

    {

    public string Name { get; set; }

    public double Weight { get; private set; }

    private string _color;

    public string Color

    {

    get { return _color; }

    set { _color = value; }

    }

    public void MakeSound()

    {

    Console.WriteLine(Sound);

    }

    }

    3、结构和类的一个区别: 现在上面两个都没有显式的构造函数,如果给它们加上显式的构造函数:

    ?

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    public struct Point

    {

    public int X { get; set; }

    public int Y { get; set; }

    public Point(int X, int Y)

    {

    this.X = X;

    this.Y = Y;

    }

    }

    如果我们进行实例化,可以发现隐式构造函数仍然可用:

    ?

    1

    2

    Point p = new Point();

    Point P = new Point(10, 12);

    但同时我们就不能在结构中再定义一个无参数的构造函数了,

快速入门C#编程之struct和class对比

电脑资料

快速入门C#编程之struct和class对比》(https://www.unjs.com)。而对于类,如果我们没有为类写任意的构造函数,那么C#编译器在编译的时候会自动的为这个类生成一个无参数的构造函数,但是一旦我们为这个类写了任意的一个构造函数的时候,这个隐式的构造函数就不会自动生成了。

最新文章