简体   繁体   中英

C# generics: How to specify type constraint and return instance of generic type

In java I can make a method with the following signature:

public <E extends Form> E makeForm(Class<E> formType) {
    //return new instance of formType
} 

You pass a class to the method that is constrained, and return an instance of that generic type. This way you can do things like:

makeForm(SomeForm.class).specificSomeFormMethod();

How can I do this in C# ? From what I've found so far it's not possible? I can make the generic type for the form instance OR for the type parameter, but not for both, and I also don't know how to constrain a Type parameter to be only of a specific class.

I'm not quite sure how to label this, so that might be my issue as well. Perhaps I'm overthinking it? I need another person's view!

I think you mean you want generic type constraints:

public E MakeForm<E>() where E : Form { }

The where indicates the start of the type constraints. Here it says that E should be or derive from Form .

You call it like this:

MyFormType form = MakeForm<MyFormType>();

When you just have the type, and nothing more, you can use this:

public Form MakeForm(Type formType)
{
    return Activator.CreateInstance(formType) as Form;
}

Form form = MakeForm(typeof(MyFormType));

You can use the new() type constraint which allows calls to the generic type's default constructor.

public class MakeForm<E> where E : FormType, new()
{
    // Method which returns a new E
    public E MakeForm()
    {
        return new E();   // this works because of the new() constraint
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM