静的クラスと通常のクラスのどちらを優先すべきでしょうか? または、それらの違いは何でしょうか?
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 :)
}
}
ベストアンサー1
静的クラスには、複数回インスタンス化できない静的オブジェクトが含まれます。通常、静的クラスは、計算、一般的な処理パターン、文字列出力形式などを提供する静的メソッドを格納するために使用されます。静的クラスは軽量で、インスタンス化の必要がありません。
たとえば、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;
}
}