开发者

Generic Method to Populate a List Cannot Create T()

开发者 https://www.devze.com 2023-02-23 06:56 出处:网络
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?

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>();
开发者_如何学C        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);
0

精彩评论

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

关注公众号