C#静态类为什么要用?

Sha*_*owG 22 c# static class

可能重复:
何时在C#中使用静态类

我将我的类设置为静态很多,但我不确定何时使用静态或不使用静态或不同之处.

有人可以解释一下吗?

Dyl*_*ith 31

使类静态只会阻止人们尝试创建它的实例.如果你的所有类都是静态成员,那么将类本身保持为静态是一个好习惯.

  • 如果我们将所有成员都设置为静态,为什么将类设为静态是一个好习惯?使类本身成为静态的优势是什么? (5认同)
  • 但为此目的,您可以声明一个私有构造函数并使类Singleton.据我所知,静态类将始终保留在内存中,从而产生开销,但普通的单例类不会. (5认同)
  • 它会阻止人们尝试实例化它 (2认同)

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)