C#示例学习(二)-使用委托传值

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应用程序时用的子窗体使用委托给父窗体回传值,当然给子窗体写的事件更好。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值