zoukankan      html  css  js  c++  java
  • C#:类和结构

    1. 类和结构:

    类定义了每个类对象(称为实例)可以包含什么数据和功能。

    结构与类的关系:

    • 区别是它们在内存中的存储方式(类是存储在堆(heap)上的引用类型,而结构式存储在堆栈(stack)上的值类型)、访问方式和一些特征(如结构不支持继承)
    • 在语法上,结构用关键字struct来声明,类用关键字class
    • 都是用关键字new来声明实例

    2. 类成员:类中的数据(字段,常量,事件)和函数(提供了操作类中数据的某些功能,包括方法、属性、构造函数和终结器、运算符以及索引器)

    public: 在类的外部可以直接访问它们

    private:只能在类中的其他代码来访问

    protected:表示成员仅能由该成员所在的类及其派生类访问

    • 数据成员:静态数据(与整个类相关),实例数据(类的每个实例都有它自己的数据副本)
    • 构造函数: 是在实例化对象的时候自动调用的函数。它们必须与所属的类同名,且不能有返回类型。

    using System;

    namespace ConsoleApplication3

    {

    class Program

    {

    staticvoid Main(string[] args)

    {

    // Calling some static functions

    Console.WriteLine("Pi is"+MathTest.GetPi());

    int x = MathTest.GetSquareOf(5);

    Console.WriteLine("Square of 5 is"+ x);

    // Calling non-static methods

    MathTest math = newMathTest();

    math.value = 30;

    Console.WriteLine("Value field of math variable contains"+ math.value);

    Console.WriteLine("Square of 30 is"+ math.GetSquare());

    }

    }

    class MathTest

    {

    public int value;

    public int GetSquare()

    {

    return value * value;

    }

    public static int GetSquareOf(int x)

    {

    return x * x;

    }

    public static double

    GetPi()

    {

    return 3.14159;

    }

    }

    }

  • 相关阅读:
    ECMAScript 2016(ES7) 知多少
    PyCharm连接远程服务器
    PyCharm远程开发和调试
    SecureCRT使用帮助
    NLP文本相似度
    程序控制结构--案例
    程序控制结构--选择结构
    程序控制结构--条件表达式
    Python序列结构--集合
    Python序列结构--字典
  • 原文地址:https://www.cnblogs.com/LilianChen/p/2737797.html
Copyright © 2011-2022 走看看