【问题标题】:MSBuild15 CS0121 ambiguous 'List<T>.List(params T[])' and 'List<T>.List(params List<T>[])'MSBuild15 CS0121 不明确 'List<T>.List(params T[])' 和 'List<T>.List(params List<T>[])'
【发布时间】:2017-11-06 20:16:46
【问题描述】:

以下代码将在 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 中,此构造函数默认为。

【问题讨论】:

  • 什么电话?它会给你一个行号吗?
  • @Dave 是这条线get { return new List&lt;T&gt;(); }
  • 我知道你现在有答案了
  • 我想知道它是如何在 MSBuild12 中编译的?选择哪个重载?
  • @Evk 添加了它的图片

标签: c# msbuild-15


【解决方案1】:

问题出在下面一行:

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>();

【讨论】:

  • @Downvoter 我真的很欣赏你的推理。提前致谢。
猜你喜欢
  • 1970-01-01
  • 2019-05-20
  • 1970-01-01
  • 2021-11-26
  • 1970-01-01
  • 1970-01-01
  • 2018-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多