zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C#,入门教程(29)——修饰词静态(static)的用法详解

c#静态入门教程 详解 用法 29 static
2023-09-11 14:15:49 时间

上一篇:

C#,入门教程(28)——文件夹(目录)、文件读(Read)与写(Write)的基础知识icon-default.png?t=MBR7https://blog.csdn.net/beijinghorn/article/details/124231282 

static 是编程高频词之一。

读了一些网文,感觉很简单的事,说的不会话了,忍不住写篇短文凑凑热闹。

你这么理解吧:

(1)静态(类)就是共享单车,随便骑;

(2)非静态类就是私家车,没有钥匙开不了。

先看一个实例:

常见的数学函数:

Math.Sqrt,Math.Pow ....

都属于 System 命名空间·静态类 Math ·静态方法。

== 属于共享企业·共享单车·共享功能

完整的写法是:

double r2 = System.Math.Sqrt(2.0);

double p2 = System.Math.Pow(2.0,2.0);

翻译成白话就是:

骑着 哈罗·单车·司库拉特 或 哈罗·单车·泡妞。

微软的程序员透露说,他们是这么写的 :P

namespace Systen
{
    public static Math
    {
        public static double Sqrt(double x)
        {
            ...
        }
        public static double Pow(double x)
        {
            ...
        }
    }
}

其实把 泡妞秘籍 Pow 的代码,完全不修改,这么写,也没任何问题。

namespace MySysten
{
    public static MyMath
    {
        public static double Sqrt(double x)
        {
            ...
        }
        public static double Pow(double x)
        {
            ...
        }
    }
}

使用:

double mp2 = MySystem.MyMath.Pow(2.0,2.0);

小结:

static 可以理解为 common class or property or function(method)。

(1)static function 的参数,一般是传入的,一般不要用 class 的 property;

(2)static class 的 property function 都是 static 的;

(3)非 static class 的  property function 也可以是 static 的;

public NonstaticClass
{
	public static int TripleSum(int a, int b, int c)
	{
		return a+b+c;
	}
}

调用:

int d = NonstaticClass.TripleSum(a, b, c);

而不是:

NonstaticClass nc = new NonstaticClass();
int d = nc.TripleSum(a, b, c);

POWER BY TRUFFER.CN
BY 315SOFT.COM 

下一篇:

C#,入门教程(30)——扎好程序的笼子,错误处理 try catchicon-default.png?t=MBR7https://blog.csdn.net/beijinghorn/article/details/124182386