準備
(なし)
デザイン
- フォーム (Form1) にボタン (button1) を配置します。
- フォーム (Form1) にリストボックス (listBox1) を配置します。
サンプルコード (C#)
namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
        }
        private void button1_Click(object sender, EventArgs e)
        {
            var tc1 = new TestClass1 { x1 = 1, y1 = 2 };
            listBox1.Items.Add(tc1.x1);
            listBox1.Items.Add(tc1.y1);
        }
    }
    public class TestClass1
    {
        public int x1;
        public int y1;
    }
}
解説
クラスのインスタンス化時に、メンバー変数名を指定して初期化しています。この方法を使用すれば、コンストラクタで引数を使わずに、初期化ができます。但し、メンバー変数が public で宣言されている必要があります。
結果
動作確認環境
Visual Studio 2022 Professional (.NET 7 C#11)
ログ
初版:2016.01.19 Visual Studio 2015 Professional (C# 6.0)
