如何在使用 IoC 时使用接口扩展 UserControl

How to extend UserControl with an Interface while using IoC

使用 C#,我们正在使用 shell 表单使用的自定义用户控件。所有自定义用户控件都允许用户执行一些基本功能,例如:

保存() 验证项()

我们的用户控件正在扩展一个名为 ScopedUserControl 的 class。

public class ScopedUserControl : UserControl, IScopedControl
    {
        private ILifetimeScope _scope;

        public void SetLifetimeScope(ILifetimeScope scope)
        {
            _scope = scope;
        }

        #region IDisposable override
        private bool disposed = false;

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (!disposed)
            {
                if (disposing)
                {
                    _scope?.Dispose();
                }

                disposed = true;
            }
        }
        #endregion
    }

这里有接口​​,配合AutoFac IoC使用

   public interface IScopedControl : IDisposable
    {
        void SetLifetimeScope(ILifetimeScope scope);
    }

我想做的是让通用 shell 表单使用用户控件。该用户控件将实现一个名为 IEditBase

的接口
  public partial class ucDataGrid : ScopedUserControl, IEditBase
    {
      ...

这里是 IEditBase

  public interface IEditBase 
    {
        bool ValidateItem();
        bool Save();
    }

现在,当用户单击表单 shell 中的工具栏保存按钮时:

 public partial class frmEditShell : ScopedForm
    {
     ....
        private void tsbSave_Click(object sender, EventArgs e)
        {
            ((IEditBase)pnlControls.Controls[0]).Save();
            this.Close();
        }

我收到这个错误: System.InvalidCastException:“无法将类型 'View.ucDataGrid' 的对象转换为类型 'Interface.IEditBase'。”在这条线上:

  ((IEditBase)pnlControls.Controls[0]).Save();

由于扩展 class ScopedUserControl 中的接口,我认为我无法转换它。

我认为我的设计方法可能有缺陷,或者我遗漏了什么。感谢您的帮助。

男.

您在不同的命名空间中有 2 个名称为 IEditBase 的接口:) ucForecastWeightedEdit 实际上继承了与 ucServiceItemOnLocation 不同的接口。如果你统一它,一切都会按预期工作。