Use Form(Of T) on VS Designer

2019-02-17 18:24发布

I'm using vb.net (vs2010). I'm moving some winforms to a dll. I have a form that inherits from the one which has some subs and functions (like a test app).

My original form is: (.designer)

Partial Class Form1(Of T)
    Inherits System.Windows.Forms.Form 
....
End Class


Form itself contains code and a toolbar.

My test form is: (.designer)

Partial Class TestForm
    Inherits Form1(Of Class1)

I get "Cannot create an instance of Form1`1[T] because Type.ContainsGenericParameters is true" when VS try to load the designer. App is usable. I can build and run the project without errors, but I need to add controls and some code to each new form.

I tried many ways:

All examples are for C#, and I don't know if I'm missing something...

Is this a bad design ? I know this is a VS bug but still it seems everyone fixed it by these links.

EDIT:

I'm building a DLL. Form1 is on this DLL and TestForm is in a new project. Those links works if I'm in the same project (a.k.a. the dll).

Thanks!

1条回答
Fickle 薄情
2楼-- · 2019-02-17 18:46

Is this a bad design ? I know this is a VS bug

Bad design, not a VS bug. What you are trying to do is fundamentally incompatible with the way the Winforms designer works. It has strong WYSIWYG support, the designer creates an instance of the form's base class and allows code in that base class to run at design time. Which is why, for example, you can set the BackgroundImage property and it is immediately visible in the designer. The Form.OnPaintBackground() method paints it. The designer is not involved at all, it just sets the property.

To make that work, it must be able to create the base class object. It can't in your code, it doesn't know what kind of T to use. Not an issue when you design Form1, the T isn't needed yet since it derives from Form and creating an instance of Form is not a problem. Big issue when you design TestForm.

You'd probably argue that it should use Class1 as the T. It doesn't, the odds that it can use Reflection to discover the generic type argument from TestForm are exceedingly low. That requires the type to be compiled first. That's a chicken-and-egg problem at design time, the TestForm class gets compiled after you design it, not before or while you design.

It's not like you completely cannot use your approach. It builds and runs just fine. You just have to live without design time support for TestForm. That's usually a deal breaker, you have to re-consider your design.

查看更多
登录 后发表回答