C#类的一些基础知识(静态方法可以不用实例化调用)

将类成员函数声明为public static无需实例化即可调用类成员函数

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;
        }
    }
}

反之,如果不声明为static,即使和Main方法从属于同一个类,也必须经过实例化

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;
        }
    }
}
posted @   夜月之光  阅读(1048)  评论(0编辑  收藏  举报
编辑推荐:
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
阅读排行:
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 【.NET】调用本地 Deepseek 模型
点击右上角即可分享
微信分享提示