注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

随机过程

http://superware.blog.163.com

 
 
 

日志

 
 

Static Members of a C# Class  

2014-06-12 23:23:16|  分类: 默认分类 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

    We can define class members as static using the static keyword. When we declare a member of a class as static, it means no matter how many objects of the class are created, there is only one copy of the static member.

    The keyword static implies that only one instance of the member exists for a class. Static variables are used for defining constants because their values can be retrieved by invoking the class without creating an instance of it. Static variables can be initialized outside the member function or class definition. You can also initialize static variables inside the class definition.


    当一个类的成员被定义为 static,则意味着不管这个类的多少个对象被产生出来,这些对象共享一个 static 成员

    关键字 static 暗示:一个类无论产生多少个对象,每个对象只共享一个 static 成员。static 变量用于定义常量,因为其值可以由类直接调用,而不必由类的实例调用。

    static 变量可以在成员函数或类的外部初始化,也可以在类定义中初始化。


1.  Static variables

using System;
namespace StaticMemberVariableApplication
{
class StaticMemberVariable
{
public static int num = 4; // initialized out side the member function

public void CountNum()
{
num++;
}

public int GetNum()
{
return num;
}
}

class StaticMemberVariableMain
{
static void Main(string[] args)
{
StaticMemberVariable sv_a = new StaticMemberVariable();
StaticMemberVariable sv_b = new StaticMemberVariable();
sv_a.countNum();
sv_a.countNum();
sv_a.countNum();
sv_b.countNum();
sv_b.countNum();
sv_b.countNum();
Console.WriteLine("Variable num for sv_a: {0}", sv_a.GetNum());
Console.WriteLine("Variable num for sv_b: {0}", sv_b.GetNum());
}
}
}

The result:

Variable num for sv_a: 10

Variable num for sv_b: 10

2. Static member function

    You can also declare a member function as static. Such functions can access only static variables. The static functions exist even before the object is created. The following example demonstrates the use of static functions:

using System;
namespace StaticMemberFunctionApplication
{
class StaticMemberFunction
{
public static int num = 2;

public void CountNum()
{
num++;
}
public static int GetNum()
{
return num; // 只能访问 static 成员变量
}
}

class StaticTester
{
static void Main(string[] args)
{
StaticMemberFunction s = new StaticMemberFunction();
s.CountNum();
s.CountNum();
s.CountNum();


// 静态成员函数可以由类名直接访问,而不需要有类的实例来访问。

Console.WriteLine("Variable num: {0}", StaticMemberFunction.GetNum());
}
}
}

The result:

Variable num: 5

  评论这张
 
阅读(79)| 评论(0)
推荐

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017