|
■No99455 (魔界の仮面弁士 さん) に返信
> ■No99451 (あいす さん) に返信
> (案2) インスタンスそのものは公開せず、フラグ操作部だけを公開する
> public partial class Form1 : Form
> {
> private readonly TestClass testClass = new TestClass();
> public void ChangeFlag(bool newValue)
> {
> testClass.TestFlag = newValue;
> }
> }
案2でサンプル書いてみました。
public partial class Form1 : Form
{
private TestClass testClass;
private Form2 form2;
public Form1()
{
InitializeComponent();
testClass = new TestClass();
testClass.YourEventName += TestClass_YourEventName;
form2 = new Form2();
form2.Show(this);
}
public void SetFlag(bool flag)
{
testClass.TestFlag = flag;
}
private void TestClass_YourEventName(object sender, TestClass.HogeEventArgs e)
{
if (e.TestFlag)
{
label1.Text = "true";
}
else
{
label1.Text = "false";
}
}
}
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
((Form1)Owner).SetFlag(true);
}
private void button2_Click(object sender, EventArgs e)
{
((Form1)Owner).SetFlag(false);
}
}
class TestClass
{
public class HogeEventArgs : EventArgs
{
public HogeEventArgs(bool testFlag)
{
TestFlag = testFlag;
}
public bool TestFlag { set; get; }
}
public event EventHandler<HogeEventArgs> YourEventName;
protected virtual void OnYourEventName(HogeEventArgs e)
{
YourEventName?.Invoke(this, e);
}
private bool _TestFlag = false;
public bool TestFlag
{
set {
this._TestFlag = value;
OnYourEventName(new HogeEventArgs(this._TestFlag));
}
get { return this._TestFlag; }
}
}
|