现在的位置: 网页制作教程网站制作教程 >正文
C#

C#中结构介绍

发表于2017/3/1 网站制作教程 0条评论 ⁄ 热度 1,820℃

本文介绍C#的结构。

1.简单示例

// 定义结构
public struct Person
{
    public string name;
    public int age;
}
class Program
{
    static void Main(string[] args)
    {
        Person p = new Person();    // 实例化结构
        p.name = "Rain Man";
        p.age = 26;
        Console.WriteLine(p.name + ", " + p.age.ToString());    // 输出: Rain Man, 26
    }
}

2.结构的构造函数

结构同样可以拥有构造函数,例如上例可以使用下面的程序实现;

public struct Person
{
    public string name;
    public int age;
    public Person(string n, int a)
    {
        this.name = n;
        this.age = a;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person p = new Person("Rain Man", 26);            // 实例化并调用构造函数
        Console.WriteLine(p.name + ", " + p.age.ToString());    // 输出: Rain Man, 26
    }
}

3.结构的实例化可以不使用 new 关键字

public struct Person
{
    public string name;
    public int age;
    public Person(string n, int a)
    {
        this.name = n;
        this.age = a;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person p;    // 由于未使用new关键字,因此不会调用Person的构造函数
        p.name = "Rain Man";
        p.age = 26;

        Console.WriteLine(p.name + ", " + p.age.ToString());    // 输出: Rain Man, 26
    }
}

4.结构的运算符重载

public struct Person
{
    public string name;
    public int age;
    public Person(string n, int a)
    {
        this.name = n;
        this.age = a;
    }

    // 运算符重载必须为:static
    // 函数的返回类型为: Person
    // 函数的参数类型为: Person
    public static Person operator +(Person p1, Person p2)
    {
        Person p;
        p.name = p1.name + " and " + p2.name;
        p.age = p1.age + p2.age;
        return p;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person p1 = new Person("Tom", 26);
        Person p2 = new Person("Jerry", 10);

        Person p = p1 + p2;   // 使用运算符(+)重载
        Console.WriteLine(p.name + ", " + p.age.ToString());    // 输出: Tom and Jerry, 36
    }
}

5.结构与类的区别

从上面的示例可以看出结构和类很相似,一般来讲结构能够实现的功能,类都可以实现。 结构体作为一种自定义的数据类型,具有以特点:

  • 值类型,相比“类”而言对内存开销较小;
  • 不能够继承,不能够作为一个类的“基类”;
  • 结构体继承自object类。
  • 暂无评论