C#でif / elseとswitch-caseを使用する場合の違いは何ですか?
Switchは、一致式とのパターンマッチに基づいて、候補のリストから実行する単一のスイッチセクションを選択する選択ステートメントです。
switchステートメントは、1つの式が3つ以上の条件に対してテストされる場合に、if-else構文の代わりに使用されることがよくあります。
Switchステートメントの方が高速です。 switchステートメントの平均比較数は、ケースの数に関係なく1になるため、任意のケースのルックアップはO(1)
です。スイッチの使用 −
例
class Program{
public enum Fruits { Red, Green, Blue }
public static void Main(){
Fruits c = (Fruits)(new Random()).Next(0, 3);
switch (c){
case Fruits.Red:
Console.WriteLine("The Fruits is red");
break;
case Fruits.Green:
Console.WriteLine("The Fruits is green");
break;
case Fruits.Blue:
Console.WriteLine("The Fruits is blue");
break;
default:
Console.WriteLine("The Fruits is unknown.");
break;
}
Console.ReadLine();
}
Using If else
class Program{
public enum Fruits { Red, Green, Blue }
public static void Main(){
Fruits c = (Fruits)(new Random()).Next(0, 3);
if (c == Fruits.Red)
Console.WriteLine("The Fruits is red");
else if (c == Fruits.Green)
Console.WriteLine("The Fruits is green");
else if (c == Fruits.Blue)
Console.WriteLine("The Fruits is blue");
else
Console.WriteLine("The Fruits is unknown.");
Console.ReadLine();
}
} -
文字列とC#の文字列の違いは何ですか?
StringはSystem.Stringを表しますが、stringはSystem.StringのC#のエイリアスです- 例 string str = "Welcome!"; 必須ではありませんが、通常、クラスを操作するときに文字列が使用されます。 string str = String.Format("Welcome! {0}!", user); 文字列はSystemのエイリアスであるため。弦。他のデータ型のエイリアスは-です 例 object: System.Object string: System.String bool: System.Bo
-
C#の内部修飾子とプライベート修飾子の違いは何ですか?
内部アクセス指定子 内部アクセス指定子を使用すると、クラスはそのメンバー変数とメンバー関数を現在のアセンブリ内の他の関数とオブジェクトに公開できます。 内部アクセス指定子を持つすべてのメンバーは、メンバーが定義されているアプリケーション内で定義されている任意のクラスまたはメソッドからアクセスできます。 以下は例です- 例 using System; namespace RectangleApplication { class Rectangle { //member variables &n