简体   繁体   中英

how to dynamical pass generic-type same as type of parameter?

I am trying to do something like this:

public static void ShowTaskPane(UserControl type)
        {            
                var item = set.OfType<typeof(type)>().FirstOrDefault();
     }

but this is not working, I want to select object of type or passed parameter. Method signature, if required, i can change it, but suggest me how to do it?

You can define your method as:

public static void ShowTaskPane<T>()
{
    var item = set.OfType<T>().FirstOrDefault();
}

and then call it like:

ShowTaskPane<UserControl>();

Or if you method is suppose to return the control then:

public T ShowTaskPane<T>()
{
    return set.OfType<T>().FirstOrDefault();
}

call it like:

var item = ShowTaskPane<UserControl>();

For comment: is there anyway I can restrict th type of T to just the subtype of UserControl?

You can specify the constraint like:

public T ShowTaskPane<T>() where T : UserControl
{
    return set.OfType<T>().FirstOrDefault();
}

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