C#中的结构体(struct)

作者:追风剑情 发布于:2019-7-1 14:39 分类:C#

示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace StructTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Books book1 = new Books();
            Books book2;

            book1.title = "title 1";
            book1.author = "author 1";
            book1.ID = 0;
            book1.onChangeTitle += OnChangeTitle;

            //按值传递
            book2 = book1;
            book2.title = "title 2";
            book2.author = "author 2";

            Console.WriteLine("book1.title=" + book1.title);
            Console.WriteLine("book1.author=" + book1.author);

            Console.WriteLine("book2.title=" + book2.title);
            Console.WriteLine("book2.author=" + book2.author);

            Console.ReadKey();
        }

        private static void OnChangeTitle()
        {

        }

        interface IBook
        {
            string GetDescription();
        }

        /**
         * 1. 结构中的字段无法赋初值
         * 2. 结构可带有方法、字段、索引、属性、运算符方法和事件
         * 3. 结构不能继承其他的结构或类
         * 4. 结构可实现一个或多个接口
         * 5. 结构成员不能指定为 abstract、virtual 或 protected
         * 6. 结构可以不使用new操作符即可被实例化(所有字段赋值后,对象才能被使用)
         * 7. 结构存储在栈中,类对象存储在堆中,结构适合描述轻量级对象
         * 8. 结构是按值传递,类对象是按引用传递
         */
        struct Books : IBook
        {
            public delegate void ChangeTitleEvent();
            public event ChangeTitleEvent onChangeTitle;

            public string title;
            public string author;
            public int ID { set; get; }

            // 可以定义有参结构函数
            public Books(string title)
            {
                //必须为所有字段赋上值
                this.title = title;
                this.author = "";
                this.ID = 0;
                this.onChangeTitle = null;
            }

            // 不能定义析构函数
            //~Books() { }

            public string GetDescription()
            {
                return string.Empty;
            }

            public override string ToString()
            {
                return title + " " + author;
            }

            public string this[int index]
            {
                get { return title; }
                set { title = value; }
            }

            // 重载+运算符
            public static Books operator +(Books b, Books c)
            {
                Books book = new Books();
                book.title = b.title + c.title;
                book.author = b.author + c.author;
                return book;
            }
        }
    }
}


运行测试
111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号