【问题标题】:Delegate method returning weird result委托方法返回奇怪的结果
【发布时间】:2015-04-12 19:47:37
【问题描述】:
        delegate bool CheckList(int lowIndex, List<int> list);
    public BO2()
    {
        InitializeComponent();
    }

    private void BO2_Load(object sender, EventArgs e)
    {
        List<int> randList = new List<int>() { 3, 4, 5, 6, 7, 8, 9, 10 };

        CheckList HasDuplicate = (int lowIndex, List<int> list) =>
            {
                Predicate<int> criteria = x => x == lowIndex;
                int topIndex = list.FindIndex(criteria);
                List<int> duplicateList = new List<int>(list);

                for (int i = topIndex; i < (list.Count - topIndex); i++)
                {
                    if (list[i] == duplicateList[i])
                    {
                        return true;
                    }
                }

                return false;
            };

        MessageBox.Show("Has copy: " + HasDuplicate.Invoke(5, randList));

我正在尝试创建一个委托函数来查看 List 是否有两个等效值。如果有,该函数将返回 true,否则返回 false。我仅出于测试目的在 8 分钟内编写了该函数,因为这种方法在某些情况下对我很有用,这就是为什么容易发生错误的原因:'D

问题: 该函数总是简单地返回真,如果你在 randList 中有一对 7,结果总是相同的,真。

注意:如果您想知道lowIndex 的含义是什么,它指定从List 开始搜索的索引。示例:lowIndex = 5,该函数将在列表中找到索引 5 并在该点之后开始搜索重复项。 :)

我不知道为什么它每次都返回 true,我不想要解决方法,无论是答案和解决方法还是仅答案。

问候,TuukkaX。

【问题讨论】:

  • 希望我没有遗漏什么,但您正在使用 list 初始化 duplicatedList。这意味着它们将具有相同的元素,因此,list[i] == duplicateList[i] 始终为真。
  • @ClaudioRedi 我看过一次,但有些事情改变了我的想法,我认为没关系:'D 继续发布你所说的答案,因为它是正确的。我想出了一种方法来解决您所注意到的整个问题,在此先感谢! :)
  • 如果您使用Distinct 扩展创建一个没有任何重复的新列表,如果没有任何重复,则两个列表中的Count() 将是相同的。跨度>
  • @ryanyuyu 我非常怀疑这是那个问题的副本,我不是要删除重复的,我是在检查是否存在。
  • @TuukkaX 这是我的错误。我正在通过 dup 屏幕搜索相关问题,我不小心按了回车键...而且无法收回标志...不过我会删除自动评论。

标签: c#


【解决方案1】:

您正在使用list 初始化duplicatedList。这意味着它们将具有相同的元素,因此,list[i] == duplicateList[i] 始终为真

【讨论】:

  • 根据您的回答,我已修复,在此先感谢! :)
【解决方案2】:

如果有人需要,这是我为解决问题而编写的代码,因为我之前没有提供。

            delegate bool CheckList(int lowIndex, List<int> list);
            CheckList HasDuplicate = (List<dynamic> list, int item) =>
            {
                if (list.Contains(item))
                {
                    list.Remove(item);
                    return list.Contains(item) ? true : false;
                }

                return false;
            };

Type基本上可以是任何类型,例如dynamic

【讨论】:

    猜你喜欢
    • 2019-05-24
    • 1970-01-01
    • 2018-01-15
    • 2012-08-08
    • 2012-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多