简体   繁体   中英

Generic Method to Populate a List Cannot Create T()

I have the generic method below which would serve its purpose if it worked! But the items.Add(new T(mo)); part wont compile because im using a constructor. Can anyone help?

    private List<T> Items<T>(string query) where T : new()
    {

        List<T> items = new List<T>();
        ManagementObjectCollection moc = new ManagementObjectSearcher(query).Get();

        foreach (ManagementObject mo in moc)
            items.Add(new T(mo));

        return items;
    }

The where T : new() syntax only allows for parameterless constructors. There are some hacks to do this, else Activator.CreateInstance should work. But a preferred approach would be an accessible Init(arg) method, perhaps via an interface (also specified via where ). So you can use:

var newObj = new T();
newObj.Init(mo);
items.Add(newObj);

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