简体   繁体   中英

I want instanciate a Generic type in C# unity3D

Hello i tried to Resize a generic tab but my probleme is to initialise new element

    List<T> Resize<T>(List<T> list, int sz)
{
    if (list.Count < sz)
    {
        while (list.Count < sz)
        {
            T someInstance = new T(); // this line is the probleme
            list.Add(someInstance);
        }
    } else if ((list.Count > sz))
    {
        list.RemoveRange(sz, list.Count);
    }
    return list;
}

Thank you <3

you need the generic constraint new() on your definition of T :

List<T> Resize<T>(List<T> list, int sz) where T: new()

Of course this assumes that every type has a parameterless constructor. ...

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