C# generics usercontrol

2020-01-29 06:37发布

问题:

I would like to define the following control:

public partial class ObjectSelectorControl<T> : UserControl where T : class 

The problem is that the designer can't resolve this. Is there a workaround to this issue?

回答1:

This works

public class Control1<T> : UserControl { ... }

public class Control2 : Control1<double> { ... }

public class Control3 : Control2 { ... }

had read it here:

Generic User Controls?



回答2:

Sounds much like what we do in our project.

There's a base class that is generic:

public partial class controlItemList<TBaseItem, TBaseItemCollection> : UserControl, IUIDispatcher
    where TBaseItem : new()
    where TBaseItemCollection : IItemCollection<TBaseItem>

Then for each use we define a non-generic version (which still couldn't be used by designer):

public class controlMessagesNonGenericParent : controlItemList<MailItem, MailItemCollection>
{
}

... and then we have derived controls that could be used in designer:

public partial class controlMessages : controlMessagesNonGenericParent
{
...
}


回答3:

There are some restrictions on what your control can or cannot do in order to be able to use the designer. Fundamentally they all revolve around the designer being able to instantiate your class (must have a parameterless constructor, can't be abstract, etc.). Because the designer has no idea what type to pass as a generic argument (and I doubt this is even a consideration), your class can't be instantiated.

Your best hope would be to create your UserControl and change the constructor to protected (this, I believe, will work, since the designer uses reflection and ignores visibility, but I'm not 100% positive). You can then inherit from that UserControl and create your generic class and call the base (protected) constructor.



回答4:

I don't believe this is possible, because the designer invokes an instance of your class. If you use generics, the designer doesn't know what type to pass into 'T'.



回答5:

https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=105876

The bug has been posted to microsoft's site and you can see that its marked as "Postponed" currently there is no solution !! .



回答6:

Use composition instead of generics. Instead of using ObjectSelectorControl, give a generic member of another type (Selector<T> maybe) and act on that object instead of trying to force yourself to be generic.



回答7:

I don't know at which point (with which C#/.NET/VS verison update), but now it is possible to create generic control the same way you create any other generic class.

If you create your UserControl in VS the standard way (i.e. by adding it through GUI), you simply add <T> in both parts of class declaration ("base" class code and the designer managed file). Actually, that is what you have in your quoted code.