LoginSignup
3
4

More than 3 years have passed since last update.

C# 備忘録1

Last updated at Posted at 2020-05-20

はじめに

業務でC#を使っていた際に詰まったところや忘れがちな所を備忘録として書きました。

  • スレッドやタスクからフォームを変更する場合

スレッドやタスクからフォームを操作するとエラーが発生する。
そのため、Invokeを使用する。

例:テキストボックス(textBox)の名称を変更する場合

sample.cs
   //フォーム上のテキストをChangedに変更
   this.Invoke(new Action<string>(this.TextChange),"Changed");

   //フォーム上のテキストボックスを変更する関数
   private void TextChange(string text)
   {
       this.textBox.Text = text;
   }

Invokeは引数の有無で以下のように使い分ける。

   //引数なし
   this.Invoke(new Action(関数));
   //引数あり
   this.Invoke(new Action<引数の型名>(関数),引数);

引数がない場合ならラムダ式を使用して、以下のように書くと便利

   //引数なし
   this.Invoke(new Action(() => {処理}));
  • 待機をする方法

例:100ミリ秒を待機する。

   System.Threading.Thread.Sleep(100)

usingを使用する場合はusing System.Threading;を宣言し、
以下のようにする。

   //100ミリ秒待機
   Thread.Sleep(100)
  • Consoleの入力

基本的にフォームを使うので、すぐに忘れてしまう。

   //文字
   string hoge1 = Console.Read();
   //1行分
   string hoge2 = Console.ReadLine();
  • Consoleの出力

入力と同じですぐに忘れてしまう

   string hoge = "test";
   //改行なし出力
   Console.Write(hoge);
   //改行あり出力
   Console.WriteLine(hoge);
  • 「」や()などで括る場合など

リソースに定義していても使えるので、便利

   string hoge = "test";
   Console.WriteLine(string.Format("「{0}」",test);

出力結果:「test」

  • 共用体を使う方法

CのunionをC#でも使えるみたいなので。
同じメモリ領域を複数の型が共有出来るので、とても便利。

   using System.Runtime.InteropServices;

   [StructLayout(LayoutKind.Explicit)]
   public struct UnionData
   {
       //0バイト目
       [FieldOffset(0)]
       public byte zero;

       //1バイト目
       [FieldOffset(1)]
       public byte one;

       //2バイト目
       [FieldOffset(2)]
       public byte two;

       //3バイト目
       [FieldOffset(3)]
       public byte three;

       //float型
       [FieldOffset(0)]
       public float floatData;

       //int型
       [FieldOffset(0)]
       public int intData;
   }   

共用体を使用したサンプル

       //共用体の宣言
       UnionData data = new UnionData();

       //int型にのみ値を代入
       data.intData = 1094861636;
       
       //それぞれの値を出力
       
       //0バイト目
       Console.WriteLine(Convert.ToChar(data.zero));

       //1バイト目
       Console.WriteLine(Convert.ToChar(data.one));

       //2バイト目
       Console.WriteLine(Convert.ToChar(data.two));

       //3バイト目
       Console.WriteLine(Convert.ToChar(data.three));

       //int型
       Console.WriteLine(string.Format("int = {0:d}",data.intData));

       //float型
       Console.WriteLine(string.Format("float = {0:0.000000}", data.floatData));

出力結果
出力サンプル.png

おわりに

まだまだ、わからないことや知らないことが多いので、勉強しないといけないです…。
データベースとかも勉強したい…

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4