C#static

只能用类名调用静态成员(用"类名.???")

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

namespace ConsoleApplication3
{
    class AA
    {
        static int a;
        public static void set(int a)
        {
            AA.a = a;
        }
        public static int get()
        {
            return a;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            AA.set(123);
            Console.WriteLine(AA.get());            
        }
    }
}

用实例来调用是非法的:
    AA t = new AA();
            t.set(123);//报错“无法使用实例引用来访问成员“ConsoleApplication3.AA.set(int)”;请改用类型名来限定它”

与C++有很大不同

C++例:

#include<iostream>
#include<cstring>
#include"includeAA.h"

using namespace std;

int main()
{
    cout<<AA::a<<endl;
    AA t;
    cout<<t.a<<endl;
}

------------------------------
#ifndef AA_H
#define AA_H


class AA
{
    public:
        AA();
        virtual ~AA();
        static int a;
    protected:
    private:
};

#endif // AA_H

-----------------------------
#include"E:我C++试验staticincludeAA.h"

int AA::a = 0;//一定要写这一句,否则报错"undefined reference to `AA::a'"
AA::AA()
{
    //ctor
}

AA::~AA()
{
    //dtor
}

C++中static即可用类名调用又可用实例来调用,且用类名时为"类名::???"



可以有静态构造函数,会最早被调用,静态构造函数不能加访问权限的关键字(如public等),它可以完成初始化器无法完成的设定工作(但只能做一次)。

原文地址:https://www.cnblogs.com/wos1239/p/4382184.html