C#チートシート
ベースクラスの取得
C++のthisでベースクラスにアクセスしたい場合のC#版。
普通にアップキャストする。
ファイルのフルパスからディレクトリを取得
Path.GetDirectoryName(fullPath)を使う。内部処理はパスとして適切な文字列かチェックし、ファイル名部分をカットしているだけ。
ファイル出力
// 新規作成 File.WriteAllText(@"C:\temp\output.txt", "Hello."); // 追記 File.AppendAllText(@"C:\temp\output.txt", "Hello.");
ログ出力
int val1 = 1; int val2 = 2; System.Console.WriteLine("val1: {0} val2: {1}\n", val1, val2);
配列を宣言して初期化リストで初期化する
int[] array1 = new int[] { 1, 3, 5, 7, 9 }; int[] array2 = { 1, 3, 5, 7, 9 }; // インスタンス化を省略できる
std::vector<T>相当のコンテナ
using System.Collections.Generic; List<int> intArray = new List<int> { 1 }; intArray[0] = 4; intArray.Add(2); System.Console.WriteLine("arraySize: {0}\n", intArray.Count);
テキストファイルからラインを読み込んで任意セパレータでstringの配列にする
string s = "comma separated some string"; string[] values = s.Split(',');
stringの先頭を大文字にする
string str = "hoge"; string temp = char.ToUpper(str[0]) + str.Substring(1);
stringの指定位置から指定文字数分を削除する
string ret = "a;;" int removeCount = 2; int pos = ret.Length - removeCount; string removedStr = ret.Remove(pos, removeCount); // ;; を削除
ディレクトリ内のファイルパス一覧を作成する
string srcDir = @"D:\prj\software\codegeneration\CommaSeparatedResource\Resource"; string[] filePaths = Directory.GetFiles(srcDir);
cf. C# examples
Typeで分岐する
typeofを使用する。switchよりif文を使うのが綺麗。
if (serializerType == typeof(Generator.GpuDescriptor.GpuDescriptorAccessorGenerator)) { }
参考:
https://stackoverflow.com/questions/43080505/c-sharp-7-0-switch-on-system-type
コメントを残す