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应用程序时用的子窗体使用委托给父窗体回传值,当然给子窗体写的事件更好。
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应用程序时用的子窗体使用委托给父窗体回传值,当然给子窗体写的事件更好。