zoukankan      html  css  js  c++  java
  • 结构体&类C#

    网上有很多关于结构体和类的介绍,但是想想还是放到自己院子里比较好(完善/修改 再 完善 再 修改)

    结构是一种值类型,通常用来封装一组相关的变量,结构中可以包含构造函数、常量、字段、方法、属性、运算符、事件和嵌套类型等,但是如果同时包含上述几个类型则应该

    考虑使用类。

    结构的特点:

    ·结构是属于值类型

    ·向方法传递结构时,结构是通过传值方式传递的,而不是作为引用传递的。

    ·结构的实例化可以不用new运算符

    ·结构可以声明构造函数,但他们必须带参数(

    结构不能声明默认构造函数——没有参数的构造函数,或析构函数。

    结构的副本由编译器自动创建和销毁,因此不需要使用默认构造函数和析构函数。实际上,编译器通过为所有字段赋予默认值(参见默认值表)来实现默认构造函数

    ·一个结构不能从另一个结构或类继承

    ·结构可以实现接口

    ·尽管结构的静态字段可以初始化,结构实例字段声明还是不能使用初始值设定项。

    聊了些特点,下面举个小例子大家参考下:

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

    namespace _
    {
        class Program
        {
            public struct Rect     //定义一个矩形结构
            {
                public double width;  //矩形的宽
                public double height; //矩形的高
                /// <summary>
                /// 构造函数,初始化矩形的宽和高
                /// </summary>
                /// <param name="x">矩形的宽</param>
                /// <param name="y">矩形的高</param>
                public Rect(double x, double y)
                {
                    width = x;
                    height = y;
                }
                /// <summary>
                /// 计算矩形面积
                /// </summary>
                /// <returns>矩形面积</returns>
                public double Area()
                {
                    return width * height;
                }

                public double CArea(double r)
                {
                    return 3.14 * r * r;
                }

            }
            static void Main(string[] args)
            {
                Rect rect1;              //实例化矩形结构
                rect1.width = 5;         //为矩形宽赋值
                rect1.height = 3;        //为矩形高赋值
                Console.WriteLine("矩形面积为:" + rect1.Area());
                Rect rect2 = new Rect(6, 4);  //使用构造函数实例化矩形结构
                Console.WriteLine("矩形面积为:" + rect2.Area());
                Console.WriteLine("圆的面积为:" + rect2.CArea(10));
                Console.ReadLine();
            }
        }
    }

    参考地址:http://www.cnblogs.com/lmfeng/archive/2011/08/17/2142595.html

  • 相关阅读:
    跳出iframe
    leetcode 225. Implement Stack using Queues
    leetcode 206. Reverse Linked List
    leetcode 205. Isomorphic Strings
    leetcode 203. Remove Linked List Elements
    leetcode 198. House Robber
    leetcode 190. Reverse Bits
    leetcode leetcode 783. Minimum Distance Between BST Nodes
    leetcode 202. Happy Number
    leetcode 389. Find the Difference
  • 原文地址:https://www.cnblogs.com/cntom/p/2143046.html
Copyright © 2011-2022 走看看