Skip to content

C# 1 基本

user000422 edited this page Jan 10, 2022 · 9 revisions

1文字はシングルクォーテーション、文字列はダブルクォーテーション(参考書「C# 超入門(SB creative)」より)
心得 : 継承を上手く使用し、類似する処理の重複を回避すること

変数
変数名に「ハイフン」「アンダーバー」を使わないこと(MS社より)
変数名にパラメータはCamel形式、その他はPascal形式(MS社より)
参考書「C# 超入門(SB creative)」より、Camel記法が一般的と解説
varの利点 … 変数名の位置が揃う、またMSが推奨しているため基本的にvarを使うこと

var sample = "hello"; // 型推論(値がfalseならbool判定など)
int number = 10;
string text = "hello";

// 定数 変数の型の前にconstを記述(値の書き換え不可 ※エラー)
const int money = 100;

thisthis.変数名でそのクラスのメンバにアクセス

if
{}の位置に決まりはないがプロジェクトごとに統一すべき

if(sample == 0)
{
 /* */
}
else if(sample == 1)
{
 /* */
}

// IsNullOrEmpty nullもしくは空の場合true
if(String.IsNullOrEmpty(sample)) { /* */}

ループ
基本はfor、繰り返す回数が分かっていないなど複雑な処理の場合はwhile

// for 基本型
for (int i = 0; i < array.Count; i++) { /* */ }

// foreach
foreach (var item in array) { /* */ }

// while 基本型
int life = 10;
while (life > 0) { life--; }

// while break ループを抜ける(whileが二重の場合1つのみ抜ける)
while (true)
{
  if (life < 3)
  {
    break;
  }
  life--;
}

配列

int[] xxx = new int[10]; // 宣言と同時に要素数指定
string[] sampleArray = {"red", "blue"}; // 宣言と同時に代入

sampleArray.Length; // 格納された要素数

// 多次元配列
string[,] monsters = new string[2, 2]; // 宣言と同時に要素数指定
string[,] colors = {{"red", "blue"}, {"black", "white"}}; // 宣言と同時に代入

System.Collections.Generic(コレクション)
MS社より、「System.Collections」は非推奨、「System.Collections.Generic」を推奨

/*--- List ---*/
var list = new List<string>(); // List宣言1
List<string> sampleList = new List<string>(); // List宣言2

list.Count(); // 格納された要素数(forなどで使用)
list.Add("red"); // 要素を末尾に追加 
list.RemoveAt(0); // 要素の削除(インデックス指定)
var result = list.Contains("red"); // 要素をチェック

list.Sort(); // 要素を昇順(小さい順)に並び替え(string型などの場合abc順)

// ArrayList どんな型でも格納可能、値を取得する際にキャスト必須
var arrayList = new ArrayList();

/*--- Dictionary(キーと値のペア) ---*/
Dictionary<string, int> dictionary = new Dictionary<string, int>(); // 宣言
var dictionary = new Dictionary<string, int>(); // 宣言(varにより左辺短縮形)

dictionary.Add("key1", 10); // 追加
int result = dictionary.Keys; // キー数(要素数)
string result = dictionary[key1]; // 値を取得
bool result = dictionary.ContainsKey("key1"); // キー存在確認

// foreachでDictionaryを扱う場合は、KeyValuePairを使うと便利
foreach (KeyValuePair<string, string> data in dictionary)
{
  string resultK = data.Key; // keyを取得
  string resultV = data.Value; // valueを取得
}

その他

// メソッド 基本型
int SampleA(string Name)
{
  if(Name == "Dragon")
  {
    return 10; // 戻り値
  }
}

// メソッド 戻り値なし
void SampleV() { /* */ }

// インスタンス作成(作成元のクラスの変数やメソッドを使用できる)
Monster dragon = new Monster();
dragon.name = "緑龍";

// コンストラクタ(インスタンスされた時に自動で行う処理、デフォルト値設定など)
// 必ずpublic修飾子を使う 戻り値の定義は禁止 オーバーロード可
public Monster() { this.hp = 10; }
// コンストラクタ 引数あり
public Monster(string name) { this.name = name; this.hp = 10; }
// コンストラクタ 引数なしのコンストラクタで引数ありのコンストラクタを実行(よく使われる)
public Monster() : this("スライム") { /* */ }

// 継承(継承したクラスのメソッドを使用可能)
class Dragon : Monster
{
  // 継承したMonsterクラスのメソッドを使用できる
}

// メソッドオーバーライド 継承したメソッドの中身を書き換える
public virtual void SampleC) { /* */ } // オーバーライドされるメソッドには「virtual」
public override void SampleC() { /* */ } // オーバーライドするメソッドには「override」

カプセル化 アクセス修飾子
アクセス修飾子を省略すると private として扱われる
メンバは基本的に private を使用し、意図しない値が設定されることを防ぐ
c#3以降は、プロパティ を使用し、冗長的なsetやgetの記述を簡潔にすることができる

public string address; // public 全てのクラスからアクセス可
private string name; // private 自身のクラス以外からはアクセス不可
protected int money; // protected 自身のクラスと派生クラス(継承クラス)以外からはアクセス不可

public void View() { /* */ } // メソッドにもアクセス修飾子を使用可

// set get プロパティを使わない記述
public void SetName() { this.hp = hp; }
public string GetName() { return this.name; }

// set get プロパティ使用
public string Name
{
  set
  {
    this.name = value;
  }
  get
  {
    return this.name;
  }
}

// 外部クラスからプロパティへのアクセス
Monster monster = new Monster(); // インスタンス化
monster.Name = "スライムナイト"; // set
Console.WriteLine(monster.Name); // get

型変換

string str = "100";
int num = 100;

str = num.ToString(); // 数値を文字列に変換

int num = int.Parse(str); // 文字列を数値に変換
// 引数の値が数値以外の場合例外エラー(FormatException)
// 引数の値がintの範囲を超えているとえらー(OverflowException)

// int型に変換できない文字列を数値にする定石処理(ifで使用することも多い)
bool result = int.TryParse(str, out num);

文字列操作
連結などを何度も行う場合は StringBulder を使用すること(速度、メモリ効率が良い)

StringBulder sb = new StringBulder(); // StringBuilderインスタンス化
sb.Append("Apple"); // 末尾に追加

string[] arrays = str.Split(','); // split 文字列を指定した文字で分割する

// Replace 文字列置換 第1引数を第2引数で置換
string result = str.Replace("red", "blue");
string result = str.Replace(@"\", "/"); // エスケープシーケンスも使用可能

System

using System;

// コンソール標準出力
Console.WriteLine("Hello");

// 比較(戻り値 : 左の値 - 右の値)(文字列比較の場合は辞書順)
var numResult = num1.CompareTo(10);
var textResult = text1.CompareTo(text2);

System.IO

using System.IO;

if(File.Exists(sampleFile)) {} // ファイル存在チェック
if(Directory.Exists("samplePath/subSamplePath")) {} // ディレクトリ存在チェック

string ext = Path.GetExtension(samplePath); // ファイル名やパスから拡張子取得

Directory.Delete(samplePath); // 指定ディレクトリを削除

// 指定ディレクトリのファイルを全て削除
foreach(var file in files) {
  File.Delete(file);
}

static
staticキーワードを付けた変数やメソッドは、外部からインスタンスを作成せずに呼び出せる
外部から呼び出す場合は クラス名.staticメソッド() で呼び出す
staticメソッドの中で扱える変数はstatic変数のみ

ref修飾子 out修飾子
メソッドに引数を渡す際に、値型を渡すと呼び出し元の変数の値は変わらない(メソッド内でしか変わらない)
そこで値型の引数を ref 修飾子 を利用し渡すことで呼び出し元の変数の値も変わる
値を代入していない変数を使用する場合は out 修飾子 を使う

int num = 1; // 値型の変数
void Sample(ref int num) { num = 100; } // 引数 ref修飾子
SampleR(ref num); // メソッドを呼び出す際にも ref 必須

int hp; // 値型の変数(代入無し)
void SampleO(out int hp) { hp = 100; } // 引数 out修飾子
SampleO(out hp); // メソッドを呼び出す際にも out 必須

Clone this wiki locally