开发者

Generic method compile time error

开发者 https://www.devze.com 2023-03-23 12:31 出处:网络
The following code: private ILi开发者_高级运维st<T> DoStuff<T>() { IList<T> res = new List<T>();

The following code:

    private ILi开发者_高级运维st<T> DoStuff<T>()
    {
        IList<T> res = new List<T>();
        for (int i = 0; i < 10; i++)
        {
            T item = DoOtherStuff<T>();
            res.Add(item);
        }
        return res;
    }

    private T DoOtherStuff<T>() where T : new()
    {
        return new T();
    }

Generates the following error:

'T' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'DoOtherStuff()'

Please may somebody explain why?


Change

private IList<T> DoStuff<T>()

to

private IList<T> DoStuff<T>() where T : new()

since otherwise you can't guarantee that T has a new() constructor.


Your DoOtherStuff<T> method has the where T : new() constraint. (That is, "T must be a non-abstract type with a public parameterless constructor".)

Your DoStuff<T> method doesn't have that constraint, which means that the compiler can't guarantee that all type arguments T that can legally be used for DoStuff will meet the where T : new() constraint required by DoOtherStuff.


DoOtherStuff's T specifies that T : new(), which means it has a public parameterless constructor. DoStuff's T has no restrictions, so you might not be able to say new T(). You should add where T : new() do DoStuff.

0

精彩评论

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