組み込み型一覧 (名称は省略形: 例えば int は System.Int32 の省略形)
| 型 | 意味 | サンプル |
|---|---|---|
| sbyte | 8 ビット 符号付き整数 | sbyte val = -5; |
| byte | 8 ビット 符号なし整数 | byte val = 5; |
| short | 16 ビット 符号付き整数 | short val = -5; |
| ushort | 16 ビット 符号なし整数 | ushort val = 5; |
| int | 32 ビット 符号付き整数 | int val = -5; |
| uint | 32 ビット 符号なし整数 | uint val = 5U; |
| long | 64 ビット 符号付き整数 | long val = -5L; |
| ulong | 64 ビット 符号なし整数 | ulong val = 5UL; |
| float | 単精度浮動小数点 | float val = -1.23F; |
| double | 倍精度浮動小数点 | double val = -1.23D; |
| decimal | 10 進数 (有効桁 28) | decimal val = 1.23M; |
| bool | ブール (true または false) | bool val = true; |
| char | 文字型 (Unicode) | char val = 'a'; |
| 型 | 意味 | サンプル |
|---|---|---|
| string | 文字列型 (Unicode) | string val = "abc" |
| object | クラスのベース型 (クラス以外も object に変換できる) | object o = new MyClass(); |
namespace ConsoleApplication1
{
/// <summary>Class1</summary>
class Class1
{
/// <summary>アプリケーションのメイン エントリ ポイント</summary>
[System.STAThread]
static void Main(string[] args)
{
// 値型の変数を参照型に変換することが出来ます.
//
// 例.
int i = 1;
object o = i;
// この操作を boxing (ボックス化) と言います.また,元の値型に戻すことも出来ます.
//
// 例.
int j = (int)o;
}
}
}
// ・コンテナ クラス等に値型を格納する時等は,この機能を使って参照型として格納することになります.
namespace ConsoleApplication1
{
struct Point
{
/* インスタンス フィールド初期化子は不可
public double x = 0.0;
public double y = 1.0;
*/
public double x;
public double y;
/* パラメータの無いコンストラクタは不可
public Point()
{
x = 1.0;
y = 1.0;
}
*/
// パラメータ付きコンストラクタは可
public Point(double x, double y)
{
this.x = x;
this.y = y;
}
// メソッドは可
public void set(double x, double y)
{
this.x = x;
this.y = y;
}
/*
virtual は不可
public virtual void sset(double x, double y)
{
this.x = x;
this.y = y;
}
*/
// override は可
public override string ToString()
{
return "(" + x.ToString() + ", " + y.ToString() + ")";
}
}
/*
継承は不可
struct SubPoint : Point
{
}
*/
/// <summary>Class1</summary>
class Class1
{
/// <summary>アプリケーションのメイン エントリ ポイント</summary>
[System.STAThread]
static void Main(string[] args)
{
Point p1 = new Point();
Point p2 = new Point(10.0, 20.0);
// new しなくてもインスタンス化可能
Point p3;
}
}
}
namespace ConsoleApplication1
{
/// <summary>Class1</summary>
class Class1
{
/// <summary>アプリケーションのメイン エントリ ポイント</summary>
[System.STAThread]
static void Main(string[] args)
{
// 一次元配列
int[] a1 = new int[5];
for (int i = 0; i < 5; i++)
{
a1[i] = i + 1;
}
int[] a2 = new int[] {1, 2, 3, 4, 5};
// 多次元配列
int[,] a3 = new int[3, 2];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 2; j++)
a3[i, j] = i + j + 1;
int[,] a4 = new int[,] {{1, 2}, {3, 4}, {5, 6}};
int[,] a5 = {{1,2}, {3,4}, {5,6}, {7,8}};
// 配列の配列も可
int[][][] a6;
}
}
}
namespace ConsoleApplication1
{
/// <summary>Foo</summary>
class Foo
{
const int c1 = 1; // 可
// static const int c2 = 1; // 不可
readonly int r1 = 1; // 可
static readonly int r2 = 1; // 可
public Foo()
{
// c1 = 2; // 不可
r1 = 2; // 可
}
private void foo()
{
// c1 = 2; // 不可
// r1 = 2; // 不可
}
}
/// <summary>Class1</summary>
class Class1
{
/// <summary>アプリケーションのメイン エントリ ポイント</summary>
[System.STAThread]
static void Main(string[] args)
{}
}
}
namespace ConsoleApplication1
{
/// <summary>Class1</summary>
class Class1
{
/// <summary>アプリケーションのメイン エントリ ポイント</summary>
[System.STAThread]
static void Main(string[] args)
{
int[] a = new int[] {3, 4, 5, 7, 9, 1, 3};
int sum = 0;
foreach (int n in a)
{
sum += n;
}
}
}
}
namespace ConsoleApplication1
{
/// <summary>Foo</summary>
class Foo
{
// プロパティ
public int n
{
get
{ return n_; }
set
{ n_ = value; }
}
private int n_;
}
/// <summary>Class1</summary>
class Class1
{
/// <summary>アプリケーションのメイン エントリ ポイント</summary>
[System.STAThread]
static void Main(string[] args)
{
Foo foo = new Foo();
foo.n = 1;
int n = foo.n;
}
}
}
namespace ConsoleApplication1
{
/// <summary>Class1</summary>
class Class1
{
private static void foo ( int n)
{
int m = n; // 可
n = 1; // Main 側の値は不変
}
private static void fooRef(ref int n)
{
int m = n; // 可
n = 1; // Main 側の値が変わる
}
private static void fooOut(out int n)
{
// int m = n; // 不可
n = 1; // Main 側の値が変わる
}
/// <summary>アプリケーションのメイン エントリ ポイント</summary>
[System.STAThread]
static void Main(string[] args)
{
int n = 0;
foo ( n); // 可
// fooRef( n); // 不可
fooRef(ref n); // 可
// fooOut( n); // 不可
fooOut(out n); // 可
int m;
// foo ( m); // 不可
// fooRef(ref m); // 不可
fooOut(out m); // 可
}
}
}
namespace ConsoleApplication1
{
class Test
{
// クラス メソッド
public static void f1(string s)
{
System.Console.WriteLine("Test.f1({0})", s);
}
// インスタンス メソッド
public void f2(string s)
{
System.Console.WriteLine("Test.f2({0})", s);
}
}
class Class1
{
// デリゲート
private delegate void Function(string s);
static void Main(string[] args)
{
// オブジェクトの作成
Test test = new Test();
Function function;
// デリゲートの作成
function = new Function(Test.f1);
// テスト
function("1. ABC");
// デリゲートの作成
function = new Function(test.f2);
// テスト
function("2. あいうえお");
// マルチキャスト デリゲート
function = new Function(Test.f1);
function += new Function(test.f2);
function += new Function(Test.f1);
function -= new Function(test.f2);
function -= new Function(test.f2);
function += new Function(test.f2);
// テスト
function("3. 安以宇");
}
}
}
namespace ConsoleApplication1
{
class Observer
{
// イベント ハンドラ
public void handler(object sender, System.EventArgs arg)
{
System.Console.WriteLine("Observer.handler({0}, {1})", sender.ToString(), arg.ToString());
}
}
class Window
{
// デリゲート
public delegate void OnClick(object sender, System.EventArgs arg);
// イベント
public event OnClick click;
// テスト用
public void test()
{
if (click != null) // null チェックしないとハンドラが登録されていない時に例外が発生する
click(this, System.EventArgs.Empty);
}
}
class Class1
{
static void Main(string[] args)
{
// オブジェクトの作成
Window window = new Window ();
Observer observer1 = new Observer();
Observer observer2 = new Observer();
// イベント ハンドラの追加
window.click += new Window.OnClick(observer1.handler);
window.click += new Window.OnClick(observer2.handler);
// テスト
window.test();
}
}
}
namespace ConsoleApplication1
{
/// <summary>Foo クラス</summary>
class Foo
{
public Foo()
{}
public void function()
{}
public static int add(int n1, int n2)
{
return n1 + n2;
}
public int proper
{
get
{
return n;
}
set
{
n = value;
}
}
private int n;
}
/// <summary>Class1 クラス</summary>
class Class1
{
/// <summary>アプリケーションのメイン エントリ ポイント</summary>
[System.STAThread]
static void Main(string[] args)
{
getTypeInfomation ();
getMemberInfomation();
callMember ();
getClassInfomation ();
getAllInfomation ();
}
/// <summary>型情報の取得</summary>
private static void getTypeInfomation()
{
System.Console.WriteLine("型情報の取得");
System.Type fooType = typeof(Foo);
System.Console.WriteLine(fooType);
Foo c = new Foo();
fooType = c.GetType();
System.Console.WriteLine(fooType);
fooType = System.Type.GetType("ConsoleApplication3.Foo");
System.Console.WriteLine(fooType);
System.Console.WriteLine();
}
/// <summary>メンバーの取得</summary>
private static void getMemberInfomation()
{
System.Console.WriteLine("メンバーの取得");
System.Type fooType = typeof(Foo);
System.Reflection.FieldInfo [] fi = fooType.GetFields ();
System.Reflection.MethodInfo [] mi = fooType.GetMethods ();
System.Reflection.PropertyInfo[] pi = fooType.GetProperties();
System.Reflection.MemberInfo [] ai = fooType.GetMembers ();
printMembers(fi);
printMembers(mi);
printMembers(pi);
printMembers(ai);
System.Console.WriteLine();
}
/// <summary>メンバーの呼び出し</summary>
private static void callMember()
{
System.Console.WriteLine("メンバーの呼び出し");
System.Type fooType = typeof(Foo);
object[] arg = new object[] {1, 2};
try
{
object result = fooType.InvokeMember("add",
System.Reflection.BindingFlags.Default | System.Reflection.BindingFlags.InvokeMethod,
null, null, arg);
System.Console.WriteLine ("{0} + {1} = {2}", arg[0], arg[1], result);
result = fooType.GetMethods()[4].Invoke(new Foo(), arg);
System.Console.WriteLine("{0} + {1} = {2}", arg[0], arg[1], result);
}
catch (System.Reflection.TargetParameterCountException)
{
System.Console.WriteLine("例外: 引数の数が違っています.");
}
catch (System.ArgumentException)
{
System.Console.WriteLine("例外: 引数が不適当です.");
}
catch (System.MemberAccessException)
{
System.Console.WriteLine("例外: メンバーへのアクセスに失敗しました.");
}
System.Console.WriteLine();
}
/// <summary>クラスの取得</summary>
private static void getClassInfomation()
{
System.Console.WriteLine("クラスの取得");
System.Type fooType = typeof(Foo);
System.Reflection.Assembly a1 = fooType.Module.Assembly;
System.Reflection.Assembly a2 = System.Reflection.Assembly.LoadFrom("ConsoleApplication3.exe");
System.Type[] types1 = a1.GetTypes();
System.Type[] types2 = a2.GetTypes();
int numInterfaces = 0;
foreach (System.Type t in types1)
{
System.Console.WriteLine("Type: {0}", t);
if (t.IsInterface)
{
numInterfaces++;
}
}
System.Console.WriteLine("{0} types in the {1}.", types1.Length, fooType.Module.ToString());
System.Console.WriteLine("{0} interfaces in the {1}.", numInterfaces, fooType.Module.ToString());
System.Console.WriteLine();
}
/// <summary>全クラス・全メンバーの一覧</summary>
private static void getAllInfomation()
{
System.Console.WriteLine("全クラス・全メンバーの一覧");
System.Reflection.Assembly a = System.Reflection.Assembly.LoadFrom("ConsoleApplication3.exe");
foreach (System.Type t in a.GetTypes())
{
System.Console.WriteLine("Type: {0}", t);
printMembers(t.GetMembers());
}
System.Console.WriteLine();
}
/// <summary>メンバー表示サブルーチン</summary>
private static void printMembers(System.Reflection.MemberInfo[] ms)
{
System.Console.WriteLine("Length : {0}", ms.Length);
foreach (System.Reflection.MemberInfo m in ms)
{
System.Console.WriteLine(m);
}
System.Console.WriteLine();
}
}
}
/*
* 1. dll の作成
* ・[ファイル] - [新規作成] - [プロジェクト] - [Visual C# プロジェクト] - [クラス ライブラリ]
*/
// dll 側のソース
namespace ClassLibrary1
{
public class Foo
{
public int foo()
{
return 0;
}
}
}
/*
* 2. dll の使用
* ・使う側のプロジェクトを右クリック - [参照の追加] - [参照] - dll ファイルを指定
* ・実際に使ってみる
*/
// exe 側のソース
namespace ConsoleApplication1
{
/// <summary>Class1</summary>
class Class1
{
/// <summary>アプリケーションのメイン エントリ ポイント</summary>
[System.STAThread]
static void Main(string[] args)
{
ClassLibrary1.Foo o = new ClassLibrary1.Foo();
int n = o.foo();
}
}
}
// (コンパイルには /unsafe オプションが必要:
// プロジェクトを右クリック - [プロパティ] - [構成プロパティ] - [ビルド] - [コード生成] - [セーフモード以外のコードブロックの許可] を True に変更)
namespace ConsoleApplication5
{
/// <summary>
/// unsafe なクラス
/// </summary>
unsafe class UnsafeClass
{
public static void unsafeTest()
{
int n = 1 ;
int* pn = &n ;
int m = *pn;
System.Console.WriteLine("n({0}), *pn({1}), m({2})", n, *pn, m);
}
}
/// <summary>
/// Class1
/// </summary>
class Class1
{
/// <summary>
/// unsafe なメソッド
/// </summary>
unsafe private static void unsafeTest()
{
int n = 1 ;
int* pn = &n ;
int m = *pn;
System.Console.WriteLine("n({0}), *pn({1}), m({2})", n, *pn, m);
}
/// <summary>
/// アプリケーションのメイン エントリ ポイント
/// </summary>
[System.STAThread]
static void Main(string[] args)
{
unsafeTest();
UnsafeClass.unsafeTest();
}
}
}
// (コンパイルには /unsafe オプションが必要)
namespace ConsoleApplication6
{
/// <summary>
/// Windows API を直接呼ぶ
/// </summary>
class WindowsAPI
{
[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern int MessageBeep(uint type);
[System.Runtime.InteropServices.DllImport(
"user32.dll" ,
CallingConvention=System.Runtime.InteropServices.CallingConvention.Winapi,
CharSet=System.Runtime.InteropServices.CharSet.Ansi ,
EntryPoint="MessageBoxA" ,
ExactSpelling=false ,
PreserveSig=true ,
SetLastError=false
)]
public static extern int MessageBoxA(
uint hWindow,
[System.Runtime.InteropServices.MarshalAs(
System.Runtime.InteropServices.UnmanagedType.LPStr
)] string text ,
[System.Runtime.InteropServices.MarshalAs(
System.Runtime.InteropServices.UnmanagedType.LPStr
)] string caption,
uint type
);
[System.Runtime.InteropServices.DllImport(
"user32.dll" ,
CallingConvention=System.Runtime.InteropServices.CallingConvention.Winapi,
CharSet=System.Runtime.InteropServices.CharSet.Unicode ,
EntryPoint="MessageBoxW" ,
ExactSpelling=false ,
PreserveSig=true ,
SetLastError=false
)]
public static extern int MessageBoxW(
uint hWindow,
[System.Runtime.InteropServices.MarshalAs(
System.Runtime.InteropServices.UnmanagedType.LPWStr
)] string text ,
[System.Runtime.InteropServices.MarshalAs(
System.Runtime.InteropServices.UnmanagedType.LPWStr
)] string caption,
uint type
);
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
unsafe public static extern void FillMemory(
System.IntPtr ptr ,
uint size,
byte fill
);
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
unsafe public static extern void ZeroMemory(
System.IntPtr ptr ,
uint size
);
}
/// <summary>
/// Class1
/// </summary>
class Class1
{
/// <summary>
/// アプリケーションのメイン エントリ ポイント
/// </summary>
[System.STAThread]
static void Main(string[] args)
{
messageBoxDemo ();
fillMemoryDemo1();
fillMemoryDemo2();
}
private static void messageBoxDemo()
{
int m = WindowsAPI.MessageBeep(0);
int n = WindowsAPI.MessageBoxA(
0, "こんにちは.", "ANSI メッセージ ボックス" , 0
);
int l = WindowsAPI.MessageBoxW(
0, "こんにちは.", "Unicode メッセージ ボックス", 0
);
}
unsafe private static void fillMemoryDemo1()
{
const uint size = 10; // 配列のサイズ
byte[] buffer = new byte[size];
// buffer の 0 番目の要素への unsafe なポインタを取得
System.IntPtr ptr = System.Runtime.InteropServices.Marshal.
UnsafeAddrOfPinnedArrayElement(buffer, 0);
// API の FillMemory を呼ぶ
WindowsAPI.FillMemory(ptr, sizeof(byte) * size, 5);
foreach (byte i in buffer)
{
System.Console.WriteLine(i);
}
}
unsafe private static void fillMemoryDemo2()
{
const int size = 10; // 配列のサイズ
// プロセスのアンマネージ ネイティブ ヒープからメモリを割り当て
System.IntPtr ptr = System.Runtime.InteropServices.Marshal.AllocHGlobal(
sizeof(byte) * size
);
// API の FillMemory を呼ぶ
WindowsAPI.FillMemory(ptr, sizeof(byte) * size, 8);
byte[] buffer = new byte[size];
// アンマネージ メモリ ポインタからマネージ byte 配列にデータをコピー
System.Runtime.InteropServices.Marshal.Copy(ptr, buffer, 0, size);
// プロセスのアンマネージ ネイティブ ヒープから割り当てられたメモリを解放
System.Runtime.InteropServices.Marshal.FreeHGlobal(ptr);
foreach (byte i in buffer)
{
System.Console.WriteLine(i);
}
}
}
}
namespace ConsoleApplication7
{
/// <summary>
/// フィールドの初期化の順番の例
/// </summary>
class Foo
{
/*
* フィールドの初期化の順番は以下の通り
* 1. クラス フィールド (static なフィールド) がデフォルト値で初期化
* 2. クラス フィールドの初期化子が書かれた順番に (上から順に) 実行
* 3. (インスタンスの生成時に) インスタンス フィールドがデフォルト値で初期化
* 4. インスタンス フィールドの初期化子が書かれた順番に (上から順に) 実行
* 5. コンストラクタ内での値の代入
*/
public static int c1 = 1;
public static int c2;
public int i1 = 1;
public int i2;
public Foo()
{
i2 = 1;
}
/*
* 例.この場合,
* 1. c1 と c2 が 0 で初期化される
* 2. c1 が 1 で初期化される
* 3. (new Foo() が呼ばれた時に) i1 と i2 が 0 で初期化される
* 4. i1 が 1 で初期化される
* 5. (コンストラクタ内で) i2 に 1 が代入される
*/
}
/// <summary>
/// Class1
/// </summary>
class Class1
{
/// <summary>
/// アプリケーションのメイン エントリ ポイント
/// </summary>
[System.STAThread]
static void Main(string[] args)
{
System.Console.WriteLine("Foo.c1({0}), Foo.c2({1})", Foo.c1, Foo.c2);
Foo foo = new Foo();
System.Console.WriteLine("foo.i1({0}), foo.i2({1})", foo.i1, foo.i2);
}
}
}
Debug ビルド時と Release ビルド時の dll の管理
・開発時のフォルダ構成の例.

class Employee
{
private int id_ = 1;
private string name_;
public int id
{
get { return id_; }
}
public string name
{
get { return name_; }
set { name_ = value; }
}
}
namespace MyApplication
{
/// <summary>MyDocument</summary>
class MyDocument
{
/// <summary>Registry</summary>
class Registry
{
private const string softwareKeyName = "Software";
private const string companyName = "My Company";
private const string applicationName = "MyApplication";
private const string myTextKeyName = "MyText";
private const string footerTextKeyName = "FooterText";
private static Microsoft.Win32.RegistryKey getApplicationKey()
{
Microsoft.Win32.RegistryKey rootKey = Microsoft.Win32.Registry.CurrentUser;
Microsoft.Win32.RegistryKey softwareKey = rootKey.CreateSubKey(softwareKeyName);
Microsoft.Win32.RegistryKey companyKey = softwareKey.CreateSubKey(companyName);
Microsoft.Win32.RegistryKey applicationKey = companyKey.CreateSubKey(applicationName);
return applicationKey;
}
public static void initialize()
{
string[] text = (string[])getApplicationKey().GetValue(myTextKeyName);
if (text != null)
myText_ = text;
}
public static void end()
{
try
{
getApplicationKey().SetValue(myTextKeyName, myText_);
}
catch
{
// ...省略...
}
}
}
static MyDocument()
{
Registry.initialize();
}
public static void end()
{
Registry.end();
}
private static string[] myText_ = new string[] {"Hello", "World"};
}
/// <summary>
/// MainClass
/// </summary>
class MainClass
{
/// <summary>アプリケーションのメイン エントリ ポイント</summary>
[System.STAThread]
static void Main(string[] args)
{
// ...省略...
MyDocument.end();
}
}
}
namespace MyWindowsApplication
{
/// <summary>MainForm</summary>
class MyWindowsApplication
{
#region メイン
/// <summary>アプリケーションのメイン エントリ ポイント</summary>
[System.STAThread]
static void Main()
{
System.Windows.Forms.Application.Run(new MainForm());
}
#endregion // メイン
}
/// <summary>MainForm</summary>
class MainForm : System.Windows.Forms.Form
{
#region デザイナ変数
private System.Windows.Forms.MainMenu mainMenu;
private System.Windows.Forms.MenuItem menuItemFile;
private System.Windows.Forms.MenuItem menuItemOpen;
private System.Windows.Forms.MenuItem menuItemOption;
private System.Windows.Forms.MenuItem menuItemExit;
private System.Windows.Forms.MenuItem menuItemHelp;
private System.Windows.Forms.MenuItem menuItemFont;
private System.Windows.Forms.MenuItem menuItemAbout;
private System.Windows.Forms.TextBox textBox;
/// <summary>デザイナ変数</summary>
private System.ComponentModel.Container components = null;
#endregion // デザイナ変数
#region コンストラクタ
public MainForm()
{
// Windows フォーム デザイナ サポートに必要
InitializeComponent();
}
#endregion // コンストラクタ
#region オーバーライド
/// <summary>使用されているリソースに後処理を実行</summary><