Dyl*_*ith 31
使类静态只会阻止人们尝试创建它的实例.如果你的所有类都是静态成员,那么将类本身保持为静态是一个好习惯.
Eni*_*ate 15
如果一个类声明为static,那么变量和方法应强制声明为static.
可以将类声明为static,表示它只包含静态成员.使用new关键字无法创建静态类的实例.当加载包含类的程序或命名空间时,.NET Framework公共语言运行库(CLR)会自动加载静态类.
使用静态类来包含与特定对象无关的方法.例如,创建一组不对实例数据起作用且与代码中的特定对象无关的方法是一种常见的要求.您可以使用静态类来保存这些方法.
- >静态类的主要特性是:
例
static class CollegeRegistration
{
//All static member variables
static int nCollegeId; //College Id will be same for all the students studying
static string sCollegeName; //Name will be same
static string sColegeAddress; //Address of the college will also same
//Member functions
public static int GetCollegeId()
{
nCollegeId = 100;
return (nCollegeID);
}
//similarly implementation of others also.
} //class end
public class student
{
int nRollNo;
string sName;
public GetRollNo()
{
nRollNo += 1;
return (nRollNo);
}
//similarly ....
public static void Main()
{
//Not required.
//CollegeRegistration objCollReg= new CollegeRegistration();
//<ClassName>.<MethodName>
int cid= CollegeRegistration.GetCollegeId();
string sname= CollegeRegistration.GetCollegeName();
} //Main end
}
Run Code Online (Sandbox Code Playgroud)