C#中static关键字的作用

加了static的成员和没加static的成员有什么区别?static都能修饰什么?方法 变量?还有别的么?

1.static意思是静态,可以修饰类、字段、属性、方法
2.标记为static的就不用创建实例对象调用了,可以通过类名直接点出来
3.static三种用法:
4.用于变量前,表示每次重新使用该变量所在方法、类或自定义类时,变量的值为程序这次运行最后一次为变量赋值时的值,这个方法称为静态函数:
private void s()
{
static int a=1;
a++;
}
方法第一次调用结束后a在内存内值为2;
方法第一次调用结束后a在内存内值为3;
5.在方法(函数)前用static修饰,表示此方法为所在类或所在自定义类所有,而不是这个类的实例所有,这个方法称为静态方法:
情况一:非静态方法:
class t
{
t(....(参数,下面同))
{
~~~~(方法内容,下面同)
}
void s(....)
{
~~~~
}
}
当你在其他方法里调用这个类中的方法s,则需先声明这个类的变量如:t sd = new t(....);
再在t里调用方法:sd.s(....);
情况2:静态方法:
class t
{
t(....(参数,下面同))
{
~~~~(方法内容,下面同)
}
static void s(....)
{
~~~~
}
}
7.当你在其他方法里调用这个类中的方法s,则不用先声明这个类的变量如直接调用方法:t.s(....);
8.用于class前,说明此类型无法新建实例,简单点说这个类型的方法全是静态方法,这个类里的非静态方法是不能使用的,这个类型称为静态类.
比如C#控制台操作的Cancle类里面的成员就被标记为静态的,可以直接用Concle.直接点出来使用。
9.如果没有标记为静态就要通过创建实例对象来调用,比如说动态字符串StringBuilder就要new一个实例来调用
StringBuilder sb =new StringBuilder();
sb.xxx(); //xxx是方法名
static class t
{
~~~~
}
~~~~
class d
{
~~~~
void f(....)
{
~~~~
t v = new t();//此时程序会出现错误
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-11-24
静态分配的,有两种情况:
1. 用在类里的属性、方法前面,这样的静态属性与方法不需要创建实例就能访问,
通过类名或对象名都能访问它,静态属性、方法只有“一份”:即如果一个类新建有N个
对象,这N 个对象只有同一个静态属性与方法;
2. 方法内部的静态变量:
方法内部的静态变量,执行完静态变量值不消失,再次执行此对象的方法时,值仍存在,
它不是在栈中分配的,是在静态区分析的, 这是与局部变量最大的区别;本回答被提问者采纳
第2个回答  2011-12-01
static
static declarator

When modifying a variable, the static keyword specifies that the variable has static duration (it is allocated when the program begins and deallocated when the program ends) and initializes it to 0 unless another value is specified. When modifying a variable or function at file scope, the static keyword specifies that the variable or function has internal linkage (its name is not visible from outside the file in which it is declared).

In C++, when modifying a data member in a class declaration, the static keyword specifies that one copy of the member is shared by all the instances of the class. When modifying a member function in a class declaration, the static keyword specifies that the function accesses only static members.

For related information, see auto, extern, and register.

Example

// Example of the static keyword
static int i; // Variable accessible only from this file

static void func(); // Function accessible only from this file

int max_so_far( int curr )
{
static int biggest; // Variable whose value is retained
// between each function call
if( curr > biggest )
biggest = curr;

return biggest;
}

// C++ only

class SavingsAccount
{
public:
static void setInterest( float newValue ) // Member function
{ currentRate = newValue; } // that accesses
// only static
// members
private:
char name[30];
float total;
static float currentRate; // One copy of this member is
// shared among all instances
// of SavingsAccount
};

// Static data members must be initialized at file scope, even
// if private.
float SavingsAccount::currentRate = 0.00154;

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网