using System;
using System.Collections.Generic;
using System.Text;
namespace DelegateTest2
{
public delegate void tranDelegate(string test);
class Program
{
//類之間值的傳遞,可用於子窗體向父窗體回傳數值
static void Main(string[] args)
{
ParentClass parent = new ParentClass();
ChildClass child = new ChildClass(parent._myDele);
//父窗體給子窗體傳值簡單
child.Result = parent.Test;
Console.WriteLine("從父窗體得來的值:{0}", child.Result);
//子窗體給父窗體回傳
child.sendValue();
Console.WriteLine("從子窗體得來的值:{0}", parent.Result);
Console.ReadLine();
}
}
class ParentClass
{
private string _test = "parent";
private static string _result = "";
public tranDelegate _myDele = delegate(string test)
{
_result = test;
};
public string Result
{
set { _result = value; }
get { return _result; }
}
public string Test
{
set { this._test = value; }
get { return this._test; }
}
}
class ChildClass
{
private string _test = "child";
private string _result = "";
private tranDelegate _tranDele;
public ChildClass(tranDelegate tranDele)
{
_tranDele = tranDele;
}
public string Test
{
get { return _test; }
set { _test = value; }
}
public string Result
{
set { this._result = value; }
get { return this._result; }
}
public void sendValue()
{
if (_tranDele != null)
{
_tranDele(this._test);
}
}
}
}
模擬了Windows應用程序時用的子窗體使用委托給父窗體回傳值,當然給子窗體寫的事件更好。