开发者

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(L开发者_如何学Goist<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)
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜