开发者

Define interface for loading custom UserControls through reflection

开发者 https://www.devze.com 2022-12-30 22:32 出处:网络
I\'m loading custom user controls into my form using reflection. I would like all my user controls to have a \"Start\" and \"End\" method so they should all be like:

I'm loading custom user controls into my form using reflection. I would like all my user controls to have a "Start" and "End" method so they should all be like:

public interface IStartEnd
{
    void Start();
    void End();
}

public class AnotherControl : UserControl, IStartEnd
{            
    public void Start()
    { }

    public void End()
    { }
}

I would like an interf开发者_如何学编程ace to load through reflection, but the following obviously wont work as an interface cannot inherit a class:

public interface IMyUserControls : UserControl, IInit, IDispose
{

}


I don't see the use case, loading user controls through reflection requires knowing the type name of the control. Either use Assembly.CreateInstance if you've dynamically loaded the assembly yourself, or use the full type name with Activator.CreateInstance so that the CLR can determine what assembly needs to be loaded.

If you want to avoid specifying the user control type name then you could iterate the loaded assembly with Assembly.GetTypes() and look for a type that implements your interface. This is only going to work well if you somehow can guarantee that the assembly contains only one control.


You can enforce the constraint at runtime that the class implementing IMyUserControls : IInit, IDispose also is UserControl. It's reasonable to assume that the developers providing custom controls for your app know the requirements for the controls, so I don't see a problem with performing the check at runtime.


It sounds like what you are trying to do is very similar to the approach taken by Prism (and the Composite Application Block). Have a read at the following articles to give you an idea of what is involved:

  • http://www.isdc.ro/community/isdc-tech-zone/blogs/Implementing-Prisma-s-Regions-with-Windows-Forms.html
  • http://www.softinsight.com/bnoyes/CommentView,guid,6c53a81e-520b-4a70-86cf-fb76eb05150d.aspx#commentstart
  • http://msdn.microsoft.com/en-us/library/ms750944.aspx

There are loads of examples out there and this pattern is very widely used.

I hope this helps.

B

0

精彩评论

暂无评论...
验证码 换一张
取 消