とある科学の備忘録

とある科学の備忘録

CやPythonのプログラミング、Arduino等を使った電子工作をメインに書いています。また、木製CNCやドローンの自作製作記も更新中です。たまに機械学習とかもやってます。

C# 基礎編 - その1

バイトでC#を勉強しているのでまとめ用に書く

工事中&期間限定公開

プログラム以前

mainメソッド

C++等で最初に実行される関数を表すmain()関数は、C#ではクラス内のメソッドとして定義される

// 最小構成のプログラム
class Test {
    static void Main() {
         Console.WriteLine("Hello, World");
    }
}


コメント

/*コメント~~~*/
/*  
スラッシュとスターに囲まれた部分は、
複数行でも
コメントになります。
*/

int a = 0; // スラッシュを二個重ねると、それ以降の文末までがコメントになる。

標準出力

Console.WriteやConsole.WriteLine関数で行う

Console.Write(""改行なしで標準出力");  
Console.WriteLine("改行ありで標準出力");

// 変数の出力
const string str = "hoge";
const int  myint = 114;
Console.Write(str);
Console.Write("str の中身は" + str + "です");

// フォーマット
Console.WriteLine("str の中身は{0}です", str);
Console.WriteLine("str の中身は{0}で, myintの中身は{1}です", str, myint);
Console.Write($"str の中身は{str}です");




予約語

docs.microsoft.com

abstract      as     base          bool     break     byte     case     catch     char     checked     class
const     continue     decimal     default     delegate     do     double     else     enum     
event     explicit     extern     false     finally     fixed     float     for     foreach     goto
if      implicit     in     int     interface     internal     is     lock     long     namespace
new      null     object     operator     out     override     params     private     protected
public     readonly     ref     return     sbyte     sealed     short     sizeof     stackalloc
static     string     struct     switch     this     throw     true     try
typeof    uint     ulong     unchecked      unsafe
ushort  using  virtual   void   volatile  while




変数の型

ユーザー定義の型(classやenum等)を除くと以下の様なものがある(代表例)

sbyte System.SByte 符号付き8bit整数
byte System.Byte 符号なし8bit整数
short System.Int16 符号付き16bit整数
ushort System.UInt16 符号なし16bit整数
int System.Int32 符号付き32bit整数
uint System.UInt32 符号なし32bit整数
long System.Int64 符号付き64bit整数
ulong System.UInt64 符号なし64bit整数
char System.Char 文字
float System.Single 小数(単精度)
double System.Double 小数(倍精度)
bool System.Boolean ブール値(false、true)
decimal System.Decimal 10進数
string System.String 文字列
//宣言  :   型 変数名;
int seisu;

// 宣言 + 初期化    :   型 変数名 = 初期値
int seisu = 123:

ルール

  • `const` を型の前に着けると、コンパイル時に値が埋め込む定数となる
    • 宣言時に初期化しなければならない
    • またその値はコンパイル時に決定する必要がある。
  • readonlyを付けると、宣言時の初期化以降、読み取り専用の変数となる
    • 宣言時に初期化しなければならない
    • 初期化値は実行時まで分からなくても良い
  • var 変数名 = 初期化値;と書くと、型推論してくれる。

例:

string str = "文字列型";
int    seisuu = 10; // 整数型
uint   unsigned_int = 10; // 非負整数
bool   bool_value = true; // true or falseの真偽値
float  float_value = 3.14f; // 不動点単精度少数
double double_value = 3.14d; // 不動点倍精度少数
var annmoku = 10; // 暗黙的型付け

四則演算

//---------------------------四則演算---------------------------------
int hoge = 0;
hoge = 10   +   20; Console.WriteLine($"10   +   20 = {hoge}");
hoge = 10   -   20; Console.WriteLine($"10   -   20 = {hoge}");
hoge = 10   *   20; Console.WriteLine($"10   *   20 = {hoge}");
hoge = 10   /   20; Console.WriteLine($"10   /   20 = {hoge}");
double hoge2 = 10.0 / 20.0; Console.WriteLine($"10.0 / 20.0 = {hoge2}");;
hoge = 30   %    8; Console.WriteLine($"30   / 8  = {hoge}");// 余り出力

条件分岐

if文

Random r = new Random();
int RandomValue = r.Next(100); // 0 ~ 99 の乱数作成

if ( RandomValue < 30) {
    Console.WriteLine("RandomValue  < 30");
}else if(RandomValue < 50) {
    Console.WriteLine("30 <= RandomValue  < 50");
}else if(RandomValue < 70) {
    Console.WriteLine("50 <= RandomValue  < 70");
}else{
    Console.WriteLine("70 <= RandomValue ");  
}


演算子

a a はbより小さい
a>b aはbより大きい
a<=b a はb以下
a>=b aはb以上
a == b aとbは等しい
a != b aはbではない

for文

for(int i = 0; i< 10; i++){
    Console.Write(i);
}

// リストに対するfor文
var arr = new ArrayList(){"list 1", "list 2", "list 3", "list 4"};
foreach(string t in arr){
     Console.WriteLine(t);
}

// 辞書に対するfor文
var myDic = new Dictionary<string, int>(){
   {"a", 1}, {"b", 2}, {"c", 3}
};

foreach(KeyValuePair<string, int> t in myDic){
  Console.WriteLine($"key = {t.Key} => {t.Value}");
}

while

int iii= 0;
while(iii< 3){Console.Write(iii); iii++;}

switch

Random rd = new Random();
int  i= rd.Next(10);

switch(i){
    case 1: 
         Console.Write("i = 0");
        break;
    case 2: 
        Console.Write("i = 2");
        break;
    default:
         Console.Write("それ以外");
          break;
}

配列/リスト

// 書き方その1(固定長)
// 型名[] 変数名 = new 型名[] { 値1, 値2, ...};
string[] mylist = new string[4]{"hoge", "hjuga", "a", "aa"};
Console.WriteLine(mylist[0]);
// 書き方その2(可変長、要Cast)
// ArrayListはObject型としてデータを代入する ( = どんな型でも代入できる)
// なので、型判定は実行時に行われる。また、値を取り出すときにはCastする必要がある(Visual BasicではOption StrictをOnにした場合)
ArrayList mylist2 = new ArrayList(){
    "list 1", "list 2", "list 3", "list 4"
};
mylist2.RemoveAt(0);  // 0番目を削除
mylist2.Add("aaaaaaaaa"); // リストの最後尾に「aaaaaaaa」を加える
mylist2.Add(5); // 0~4番目の要素は文字列型だが、ArrayList なので数値を入れることもできる
Console.WriteLine(mylist2[0]);

string moji = mylist[0]; // コンパイルエラーになるかも?
string moji = (string)mylist[0]; // string型にキャストする必要がある
// 書き方その3(可変長、固定型)
// ArrayListは特定の型としてリストを作るので、それぞれの要素にはその型しか代入できない
// 取り出すとき等に型変換は必要ない

// string型で、mylist3 という変数名のList
List<string> mylist3 = new List<string>(){
    "a", "b", "c"
};
// mylist3.Add(5);// string型のリストにintを入れようとしているのでビルドエラー
mylist3.Add("aaaa");// これはOK


使い方
mylistという名前のArrayList またはListがあったとすると、

  • mylist[n] でmylistのn+1番目の要素にアクセスできる
    • 代入も可能

プロパティ(クラス内変数):

mylist.Capacity 確保している容量
mylist.Count 配列の長さ

メソッド(関数)の代表的なもの:

mylist.Add(object) objectをmylistの末尾に挿入
Insert(n, object) objectをmylistのn番目(n = int32型)に挿入
mylist.IndexOf(object) mylist中でobjectを検索し、最初に見つかったオブジェクトのインデックス (0 から始まる) を返す
mylist.Contains(object) mylist中にobjectがあればtrueを返し、ない場合はfalseを返す
mylist.Remove(object) mylist中にobjectがあれば、最初に出現したものを削除
mylist.RemoveAt(n) n+1番目の要素を削除
mylist.RemoveAt(a, b) aからbで指定された範囲の要素を削除
mylist.Clear() 全削除。Countは0になるがCapacityは0になるとは限らない
mylist.Sort() ソート

それ以外は↓に載っている
docs.microsoft.com

docs.microsoft.com

List / ArrayListでfor文

var arr = new ArrayList(){"list 1", "list 2", "list 3", "list 4"};
foreach(string t in arr){
    Console.WriteLine(t);
}

辞書

Dictionary<string, int> myDic = new Dictionary<string, int>(){
    {"a", 1}, {"b", 2}, {"c", 3}
};
Console.WriteLine(myDic["a"]);
myDic["a"] = 100;  // 代入
myDic["d"] = 100; // 新しく key-valueを作成して代入
myDic.Remove("b"); // {b : 2} のkey-valueを削除
Console.WriteLine(myDic["a"]);


// 因みに、辞書のなかの値を全て出力するには、

// 例1
foreach(KeyValuePair<string, int> t in myDic){
    Console.WriteLine($"key = {t.Key} => {t.Value}");
}

// 例2
foreach(string key in myDic.keys){
    Console.WriteLine($"{key}に相当する値は{mDic[key]}です");
}

その他:
docs.microsoft.com


関数