[英]Delegate method returning weird result
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分鍾內對該函數進行了編碼,僅出於測試目的,因為在某些情況下此方法對我很有用,所以這就是可能容易發生錯誤的原因:
問題:該函數只是始終返回true,如果randList中有7對,結果總是相同,為true。
注意:如果您想知道lowIndex
的含義是lowIndex
,它將指定要從List開始搜索的索引。 示例: lowIndex = 5
,該函數將在列表中找到5的索引,然后在該點之后開始搜索重復項。 :)
我不想知道為什么每次都返回true,所以我不需要解決方法,無論是答案與解決方法還是僅回答。
問候,TuukkaX。
您正在使用list
初始化duplicatedList
list
。 這意味着它們將具有相同的元素,因此, list[i] == duplicateList[i]
始終為true
這是我為解決該問題(如果有人需要)而編寫的代碼,因為我之前沒有提供。
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;
};
類型可以是任何類型的基本上, 動態例如。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.