C#语法回忆零散巩固(持续更新最新版)

散知识点回忆巩固,为本人开发过程中遇到的突然想不起来的知识点,进行汇总回顾,每个知识点都会有标题方便点击目录查。遇到什么就加什么,文章会越来越长,会持续上传最新版。

C# 类的静态成员

用关键字 static 进行修饰,修饰变量即为静态变量,可以通过类直接进行调用,不需要通过对应的实例(new对象来调用)。

cs 复制代码
using System;
namespace StaticVarApplication
{
    class StaticVar
    {
       public static int num;
        public void count()
        {
            num++;
        }
        public int getNum()
        {
            return num;
        }
    }
    class StaticTester
    {
        static void Main(string[] args)
        {
            StaticVar s1 = new StaticVar();
            StaticVar s2 = new StaticVar();
            s1.count();
            s1.count();
            s1.count();
            s2.count();
            s2.count();
            s2.count();         
            Console.WriteLine("s1 的变量 num: {0}", s1.getNum());
            Console.WriteLine("s2 的变量 num: {0}", s2.getNum());
            Console.ReadKey();
        }
    }
}

上述代码运行后会得到以下结果:

s1 的变量 num: 6

s2 的变量 num: 6

为什么s1、s2两个对象,结果会是6,因为

当我们声明一个类成员为静态时,意味着无论有多少个类的对象被创建,只会有一个该静态成员的副本。

关键字 static也可以用来修饰函数(方法),同理,也无需实例化即可调用该函数(方法 )。

cs 复制代码
using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = AddClass.Add(2, 3);  //编译通过
            Console.WriteLine(num);
        }
    }

    class AddClass
    {
        public static int Add(int x,int y)
        {
            return x + y;
        }
    }
}
cs 复制代码
using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            int num = Add(2, 3);  //编译错误,即使改为Program.Add(2, 3);也无法通过编译
            Console.WriteLine(num);
        }

        public int Add(int x, int y)
        {
            return x + y;
        }
    }
}
using System;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Program self = new Program();
            int num = self.Add(2, 3);  //编译通过
            Console.WriteLine(num);
        }

        public int Add(int x, int y)
        {
            return x + y;
        }
    }
}

上图由Ai给出示例代码,帮助更好分析。

相关推荐
京东零售技术20 小时前
探索无限可能:生成式推荐的演进、前沿与挑战
算法
koo36420 小时前
李宏毅机器学习笔记24
人工智能·笔记·机器学习
xyx-3v20 小时前
SPI四种工作模式
stm32·单片机·嵌入式硬件·学习
lingchen190620 小时前
多项式的积分
算法
老虎062720 小时前
黑马点评学习笔记02(Mabatis—plus)
笔记·学习
【0931】21 小时前
2024.6卷一阅读短语
学习
哲此一生98421 小时前
SpringBoot3集成Mybatis(开启第一个集成Mybatis的后端接口)
java·spring boot·mybatis
坚持编程的菜鸟21 小时前
LeetCode每日一题——在区间范围内统计奇数数目
c语言·算法·leetcode
浮游本尊21 小时前
Java学习第26天 - 微服务监控与运维实践
java
高山上有一只小老虎21 小时前
idea2025社区版设置打开的多个文件展示在工具栏下方
java·ide·intellij-idea