【问题标题】:Generic Action call assignment issue通用操作调用分配问题
【发布时间】:2012-10-02 09:32:23
【问题描述】:

我需要一种使用通用调用在表单上设置属性的方法。我有一个创建单例表单的静态类,一个主表单(MDI)进行调用,该类负责调用,知道显示、打开等。

一切都很顺利,直到我意识到我需要在表单上设置属性。我可以做到,但我希望分配发生在表单加载之前

我想出了一个方法来完成这个,至少我认为我有一个很酷的想法,但是......让我们看看代码:

    public interface IFormBase
    {
        Action<IFormBase> SetParameters { get; set; }
    }

    public class FormBase : Form, IFormBase
    {
        public Action<IFormBase> SetParameters { get; set; }

        protected override void OnLoad(EventArgs e)
        {
            if (SetParameters != null)
            {
                SetParameters.Invoke(this);
            }
            base.OnLoad(e);
        }
    }

...稍后在 FormManager 静态类中...

        public TResult GetSingleTonForm<TResult, T>(object state, Action<T> setParameters)
            where TResult : FormBase
            where T : IFormBase
        {
            Type t = typeof(T);
            FormBase f = null;

            if (f == null)
            {
                f = (FormBase)Activator.CreateInstance(t);
            }

            if (setParameters != null && f is IFormBase)
            {
                f.SetParameters = setParameters;
            }

            return (TResult)f;
        }
...

问题:

无法将类型 System.Action&lt;T&gt; 隐式转换为 System.Action&lt;blabla.IFormBase&gt;

我了解错误,我正在寻求帮助,以便制定不同的解决方案! 谢谢!

【问题讨论】:

    标签: c# winforms generics delegates


    【解决方案1】:

    这个呢:

    public T GetSingleTonForm<T>(object state, Action<T> setParameters)
                where T : FormBase, IFormBase 
            {
                Type t = typeof(T);
                FormBase f = null;
                if (f == null)
                {
                     f = (FormBase)Activator.CreateInstance(t);
                }
    
                if (setParameters != null && f is IFormBase)
                {
                    setParameters.Invoke((T)f);
                }
    
                return (T)f;
            }
    

    它确实可以编译,我认为它可以满足您的需求。这样,您也不需要在您的 FormBase 上调用 OnLoad

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-18
      • 2011-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      相关资源
      最近更新 更多