静态类和普通类有什么区别?

Pen*_*uen 18 .net c# oop

我什么时候应该选择静态课程还是普通课程?或者:他们之间有什么区别?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace staticmethodlar
{
    class Program
    {
        static void Main(string[] args)
        {
            SinifA.method1();
        }
    }

    static class SinifA 
    {
       public static void method1()
        {
            Console.WriteLine("Deneme1");
        }
    }

    public static class SinifB
    {
        public static void method2()
        {
            Console.WriteLine("Deneme2");
        }
    }
    public class sinifC
    {
       public void method3()
        {
            Console.WriteLine("Deneme3");
        }
    }

    public class sinifD : sinifC
    {
        void method4()
        {
            Console.WriteLine("Deneme4");
        }

        sinifC sinifc = new sinifC();  // I need to use it :)
    }
}
Run Code Online (Sandbox Code Playgroud)

Jef*_*Fay 30

静态类包含无法多次实例化的静态对象.通常我使用的静态类是容纳静态方法,提供计算,一般处理模式,字符串输出格式等.静态类重量轻,不需要实例化.

例如System.IO.File,静态类是静态方法Exists().您不创建File对象来调用它.你像这样调用它

System.IO.File.Exists(filePath)

而不是这样做

System.IO.File myFile = new System.IO.File(filePath);

if(myFile.Exists()) { /* do work */ }

如果在软件中需要多个对象,则使用动态类.例如,如果您有库存系统,则可能有多个Product对象,在这种情况下,您将使用此类动态类

public class Product
{

    public int    ProductID   { get; private set; }
    public string ProductName { get; private set; }
    public int    Qty         { get; set; }

    public Product( int productID, string productName, int total )
    {
        this.ProductID = productID;
        this.ProductName = productName;
        this.Qty = total;
    }       
}
Run Code Online (Sandbox Code Playgroud)


thi*_*eek 15

  • 静态类不能instantiatedinherited.
  • 静态类在输出MSIL 中标记为sealedabstract编译器.
  • 静态类的所有成员也必须是静态的.
  • 只有静态类才能托管extension methods.
  • 静态类不能用作泛型类型参数.