0

以下代码将在 MSBuild12 中编译,但在 MSBuild15 中将失败

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace Example
{
    public class List<T> : IEnumerable<T>
    {
        private readonly T[] _items;

        public List(params T[] items)
        {
            _items = items;
        }

        public List(params List<T>[] args)
        {
            _items = args.SelectMany(t => t).ToArray();
        }

        public static List<T> New
        {
            get { return new List<T>(); }
        }


        public IEnumerator<T> GetEnumerator()
        {
            foreach (var item in _items)
                yield return item;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return _items.GetEnumerator();
        }
    }
}

结果

CS0121 以下方法或属性之间的调用不明确:'List.List(params T[])' 和 'List.List(params List[])' 示例 D:\Example\Test.cs

在 MSBuild 12 中,此构造函数默认为。 显示调用的默认构造函数

4

1 回答 1

3

问题出在以下行:

public static List<T> New
{
    get { return new List<T>(); }
}

并且这是由于应该使用两个构造函数中的哪一个是模棱两可的。您可以通过提供适当的参数来指定要使用两者中的哪一个来克服此问题:

public static List<T> New => new List<T>(new T[]{});

或者

public static List<T> New => new List<T>(new List<T>{});

另一种方法是声明一个无参数的构造函数

public List()
{ 
    _items = new T[0];
}

然后有这个:

public static List<T> New => new List<T>();
于 2017-11-06T20:21:21.540 回答