VS Designer错误:GenericArguments [0],'Y'上的'X'违反了类型参数'Z'的约束

Cod*_*rDU 6 c# generics type-constraints windows-forms-designer visual-studio

我正在尝试创建从"泛型"基类继承的表单,其中该基类的泛型参数具有必须实现我的一个接口的约束.

它编译并运行得很好.我的问题在于Visual Studio设计器.它将打开表单,直到我重建项目,然后在尝试查看表单设计器时报告下面的错误,直到我重新启动Visual Studio,或删除基类中的自定义接口约束.

GenericArguments[0], 'InterfaceInBaseClassProblem.TestEntity', on 'InterfaceInBaseClassProblem.BaseWindowClass`1[EntityType]' violates the constraint of type 'EntityType'.
Run Code Online (Sandbox Code Playgroud)

第1步:创建一个界面

namespace InterfaceInBaseClassProblem
{
    public interface ITestInterface
    {
        void Func1();
    }
}
Run Code Online (Sandbox Code Playgroud)

第2步:创建一个实现接口的类

namespace InterfaceInBaseClassProblem
{
    public class TestEntity : ITestInterface
    {
        public void Func1()
        {
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

步骤3:创建一个通用基类Form,它需要一个通用参数约束,要求实现我们创建的接口

using System.Windows.Forms;
namespace InterfaceInBaseClassProblem
{
    public class BaseWindowClass<EntityType> : Form where EntityType : ITestInterface
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

第4步:现在创建一个继承自Generic Base Form的新表单,并使用TestEntity类作为参数

namespace InterfaceInBaseClassProblem
{
    public partial class Form1 : BaseWindowClass<TestEntity>
    {
        public Form1()
        {
            InitializeComponent();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

步骤5:保存您的项目并测试我正在尝试解决或解决的以下行为:

a) Close Visual Studio
b) Open Visual Studio
c) Open the Form1 class to view its designer and confirm its working
d) Close the Form1 designer you just opened
e) Rebuild the project
f) Open the Form1 class to view the error I have reported.
g) Either restart Visual Studio, or comment out the "where EntityType : ITestInterface" constraint we included with step 3 and rebuild to see it start working again
Run Code Online (Sandbox Code Playgroud)

补充说明:

  • 我已经在VS2015和2017测试了相同的结果
  • 我已在多台开发机器上测试过
  • 我对此设计的需求是在基类中以及它将执行的各种附加功能/角色,这些功能/角色需要通用的"EntityType"并要求它可以执行我添加到我的自定义接口的操作.这些泛型函数将被我声明从该基类继承的所有表单使用.

Ore*_*ell 6

如果微软看到这个,我也会遇到类似的问题。在VS2015中得到确认。我有4种形式:

public class BaseForm : Form
{
    public BaseForm() {...}
}

public class BaseSubForm<T> : Form where T : BaseForm
{
    public SubForm(T f) {...}
    public InitForm(T f) {...}
}

public partial class TestForm : BaseForm
{
    TestSubForm sf;

    public TestForm()
    {
        ...
        sf = new TestSubForm(this);
    }
}

public partial class TestSubForm : BaseSubForm<TestForm>
{
    public TestSubForm(TestForm f) : base(f)
    {
        InitializeComponent();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我构建它,它将运行,但TestSubForm不会显示在设计器中。但是,如果我从 BaseSubForm 的构造函数中删除参数......

...
public SubForm() {...}
...
sf = new TestSubForm();
...
public TestSubForm(TestForm f)
...
Run Code Online (Sandbox Code Playgroud)

我可以重新启动 Visual Studio,构建,它会显示得很好。我可以通过在我的第二阶段构造函数中传递该参数来完成InitForm,但令人恼火的是我需要两个构造函数。

设计师似乎讨厌类型类别Subclass : BaseClass<Generic>