简体   繁体   中英

A generic type as a parameter

My first question is, is it possible to specify a generic type as a parameter, secondly, is anything such as the pseudo code ive listed below possible?

I assume it will be using .net 4.0 and the dynamics modifier but i am more interested in a pre 4.0 solution.

    public static void SomeMethod(List<T> l, Type type, Control samplecontrol)
    {
     l.Add((type)samplecontrol);
    }

Edit:

Here is my solution...

    public static void FindControlRecursive<T>(Control parent, List<T> l)
    {
        foreach (var ctrl in parent.Controls)
        {
            if (ctrl.GetType() == typeof(T))
                l.Add((T)ctrl);
            if (((Control)ctrl).Controls != null && ((Control)ctrl).Controls.Count > 0)
                foreach (Control _ctrl in ((Control)ctrl).Controls)
                    FindControlRecursive<T>(_ctrl, l);
        }
    }

You mean this?

public static void SomeMethod<T>(List<T> l, T item)
{
    l.Add(item);
}

You need to add the generic type modified to the method name. That will replace your type parameter that you were trying to pass in,

public static Add<T>(List<T> l, T samplecontrol)
{
 l.Add(samplecontrol);
}

You can also add type qualifiers onto the method

public static Add<T>(List<T> l, T samplecontrol) 
    where T : Control
{
 l.Add(samplecontrol);
}

Try this

public static void YourMethodName<T>(List<T> l, Control samplecontrol)
{
    l.Add((T)samplecontrol);
}

Yes, it is possible, and has been since C# 2.0. This is probably the syntax you are looking for:

public static void AddControlToList<T>(List<T> list, Control sampleControl)
{
    list.Add((T)sampleControl)
}

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