开发者

Enforcing the value of a Type variable as special base type

I have realized my module system by forcing modules to implement an abstract class, which contains mandatory methods which will be called by the base application. Now I want to realize a configuration form for each module. I thought about returning the type of the form as a property of my module skeleton class:

public abstract class Module
{
    public abstract Type ConfigurationForm { get; }
}

When displaying the configuration form, I simply instantiate a Form of this type and call the Show() method.

The problem is, I want to force the module to return a Type which is a sub class of System.Windows.Forms.Form, as the call would fail otherwise. What is the correct way to enforce this?

I thought about encapsulating the Configuration开发者_如何学PythonForm property in another property, which checks if it is inherited from Form, but I don't think this is a clean way to accomplish this.


You could accomplish this with a generic type parameter

public abstract class Module<F> where F : Form
{
    public Type ConfigurationForm { get { return typeof(F); } }
}

But really this might make more sense:

public abstract class Module
{
    public abstract Form CreateConfigurationForm();
}

Edit: The advantage of using the 2nd option is that you can write code to work with your Module class without having to know specifically which kind of module you are dealing with


There is no way to restrict a function to return Type, which represents a type that inherits from Form. What you could do it to return the form directly:

public abstract Form CreateConfigurationForm();

or a factory method (or alternatively, factory class):

public abstract Func<Form> ConfigurationFormCreator();

Another option would be to use generics, as erash suggested.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜