準備
(なし)
デザイン
- フォーム (Form1) にボタン (button1) を配置します。
- フォーム (Form1) にリストボックス (listBox1) を配置します。
サンプルコード (C#) クラスの定義
namespace WinFormsApp1
{
public static class GLOBAL
{
public static string CustomerName;
public const double TaxRate = 0.05;
public static int TaxPrice(int iPrice, double dTax)
{
return (int)(iPrice * (1 + dTax));
}
}
}
サンプルコード (C#)
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
GLOBAL.CustomerName = "Tanaka";
}
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Add(GLOBAL.CustomerName);
listBox1.Items.Add(GLOBAL.TaxPrice(1000, GLOBAL.TaxRate));
}
}
}
解説
スタティッククラス、スタティッククラス変数、スタティックメソッドを使うことで、グローバル変数とグローバル関数を擬似的に作っています。定数には static キーワードを付けることができませんが、プロジェクト全体で使用できる定数として使うことができます。
結果
動作確認環境
Visual Studio 2022 Professional (.NET 7 C#11)
ログ
初版:2016.06.07 Visual Studio 2015 Professional (C# 6.0)
