Form之间传递参数或联动的范型代理实现

来源:互联网 发布:java 对数组随机排序 编辑:程序博客网 时间:2024/05/05 16:16

    Winform编程中经常会用到Form与Form之间传递参数或者Form1中的动作更新Form2中的数据或呈现,网路中也有很多大师写过类似的文章,本文不是想重提来说明什么,只是分享一下自己的实现和一些想法。

    先说实现好了:

    Step1:定义一个ParentChildRelateEventHandler<TEventArgs>和一个自定义EventArgs
    定义一个ParentChildRelateEventHandler<TEventArgs>目的是一个项目中可能会有多处此类的处理,那通过范型实现一个delegate模板,就不需要每个地方都重新定义一遍了;
    定义一个EventArgs的目的是Form之间传递的可能是自定义对象,所以,需要提供一个EventArgs的模板供调用时指定特定的对象类型;

using System;
using System.Collections.Generic;
using System.Text;

namespace TestForDelegate
{
    
/// <summary>
    
///  This event handler is for the relation event of parent form and child form
    
/// </summary>
    
/// <typeparam name="TEventArgs">the event arges you want to tell the event handler</typeparam>
    
/// <param name="sender">the object who fired this event</param>
    
/// <param name="e">the event arges</param>

    public delegate void ParentChildRelateEventHandler<TEventArgs>(object sender, TEventArgs e)
        
where TEventArgs : EventArgs;

    
/// <summary>
    
///  This event args is for the relation of parent form and child form
    
/// </summary>
    
/// <typeparam name="TType">The type that you want to tell the args to transfer</typeparam>

    public class ParentChildRelateEventArgs<TType> : EventArgs
    
{
        
/// <summary>
        
///  Contructor of ParentChildRelateEventArgs
        
/// </summary>
        
/// <param name="t">the Type you want to transfer</param>

        public ParentChildRelateEventArgs(TType t)
        
{
            
this.m_CustomObject = t;
        }


        
private TType m_CustomObject;
        
/// <summary>
        
///  Get or Set the object that can make you transfer it between parent form and child form
        
/// </summary>

        public TType CustomObject
        
{
            
get return m_CustomObject; }
            
set { m_CustomObject = value; }
        }

    }

}

    Step2:FormChild中暴露事件供FormParent调用

   

    Step3:Parent Form中ShowDialog调用ChildForm,并对ChildForm的事件进行实现动作

   

    这样就完成了ParentForm和ChildForm之间的对话。

    优点:Child Form和Parent Form之间解除了关联关系,故Child Form可以不依赖于Parent Form而存在,从而可以将Child Form发布成为共用的组件以便重用;采用范型实现代理和EventArgs,灵活性提高,同一个Project或多个Project都可以公用一份;EventHandler也采用范型实现,可以供使用者使用自定义的EventArgs来实现更复杂的需求;

    缺点:其实也谈不上缺点了,就是觉得不长写的人看着可能晕~呵呵

附:测试代码Solution
Download

原创粉丝点击