Windows FormアプリケーションでProgram クラスのメンバ変数やプロパティにアクセスする - C#

Windows FormアプリケーションでProgram クラスのメンバ変数やプロパティにアクセスするコードを紹介します。

概要

Windows FormアプリケーションのスタートアップクラスのProgramクラスにアクセスするコードを紹介します。
ProgramクラスはStaticクラスであることに注意が必要です。

書式

Programクラスはstaticクラスとして定義されているため、Program を記述してアクセスします。
Program.(メンバ変数名)
Program.(プロパティ名)
Program.(メソッド名)

プログラム

UI

下図のフォームを作成します。ボタンとテキストボックスを3つ配置します。

コード

下記のコードを記述します。
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace VariableScope
{
  static class Program
  {
    static public string TextValue;
    static public int MyProperty { get; set; }

    /// <summary>
    ///  The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
      TextValue = "ぺんぎんクッキー";
      MyProperty = 320;

      Application.SetHighDpiMode(HighDpiMode.SystemAware);
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new FormMain());
    }

    static public string MyFunc()
    {
      return "メソッドが実行されました。";
    }
  }
}
FormMain.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace VariableScope
{
  public partial class FormMain : Form
  {
    public FormMain()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      textBox1.Text = Program.TextValue;
      textBox2.Text = Program.MyProperty.ToString();
      textBox3.Text = Program.MyFunc();
    }
  }
}

解説

Program.cs

Program クラスにメンバ変数(TextValue)、プロパティ(MyProperty)、メソッド(MyFunc)の3つを実装しています。
  static class Program
  {
    static public string TextValue;
    static public int MyProperty { get; set; }

    /* 中略 */

    static public string MyFunc()
    {
      return "メソッドが実行されました。";
    }
  }

ProgramクラスのMain関数でApplication.Run メソッドを実行してWindows Formアプリケーションを開始する前に、 Programクラスのメンバ変数とプロパティに値を代入して設定します。
    static void Main()
    {
      TextValue = "ぺんぎんクッキー";
      MyProperty = 320;

      Application.SetHighDpiMode(HighDpiMode.SystemAware);
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new FormMain());
    }

FormMain.cs

Programクラスのメンバ変数の値、プロパティの値、メソッドの戻り値の値をそれぞれテキストボックスに表示します。
    private void button1_Click(object sender, EventArgs e)
    {
      textBox1.Text = Program.TextValue;
      textBox2.Text = Program.MyProperty.ToString();
      textBox3.Text = Program.MyFunc();
    }

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。


[button1]をクリックします。下図の文字列がテキストボックスに表示されます。Programクラスのメンバ変数やプロパティに設定した値、 実装したメソッドの戻り値がテキストボックスに表示されます。


著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
掲載日: 2021-08-15
iPentec all rights reserverd.