关于泛型的问题

-汪帆- 2010-02-09 11:00:49
我自定义了一个Rect类
在A类中定义了泛型成员List<Rect> rects = new List<Rect>();
在A对象中我取到了rects中的一个成员rect1对象
现在我想知道rect1在rects中的位置
即:rects[i] == rect1,求i

声明:不用for循环,用泛型里面的方法怎么做?
我知道有这个方法FindIndex(int startIndex, Predicate<Rect> match),但是不知道怎么用,直接把rect1传进去会报错。
...全文
116 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zishanyan 2010-02-09
  • 打赏
  • 举报
回复


using System;
using System.Collections.Generic;

public class Example
{
public static void Main()
{
List<string> dinosaurs = new List<string>();

dinosaurs.Add("Compsognathus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Oviraptor");
dinosaurs.Add("Velociraptor");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Dilophosaurus");
dinosaurs.Add("Gallimimus");
dinosaurs.Add("Triceratops");

Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}

Console.WriteLine("\nFindIndex(EndsWithSaurus): {0}",
dinosaurs.FindIndex(EndsWithSaurus));

Console.WriteLine("\nFindIndex(2, EndsWithSaurus): {0}",
dinosaurs.FindIndex(2, EndsWithSaurus));

Console.WriteLine("\nFindIndex(2, 3, EndsWithSaurus): {0}",
dinosaurs.FindIndex(2, 3, EndsWithSaurus));
}

// Search predicate returns true if a string ends in "saurus".
private static bool EndsWithSaurus(String s)
{
if ((s.Length > 5) &&
(s.Substring(s.Length - 6).ToLower() == "saurus"))
{
return true;
}
else
{
return false;
}
}
}

/* This code example produces the following output:

Compsognathus
Amargasaurus
Oviraptor
Velociraptor
Deinonychus
Dilophosaurus
Gallimimus
Triceratops

FindIndex(EndsWithSaurus): 1

FindIndex(2, EndsWithSaurus): 5

FindIndex(2, 3, EndsWithSaurus): -1
*/



这是MSDN的示例源码,在FindIndex中传入的是一个委托,比较方法是自己实现的
  • 打赏
  • 举报
回复
自己去看.net framework源代码,这是“扎进”.net技术的第一步。
  • 打赏
  • 举报
回复
用for循环又有什么不可以?

FindIndex内部就是用一个for循环来依次查找(调用match比较)的。我们来看看源代码:
public int FindIndex(int startIndex, Predicate<T> match)
{
return this.FindIndex(startIndex, this._size - startIndex, match);
}

public int FindIndex(int startIndex, int count, Predicate<T> match)
{
if (startIndex > this._size)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.startIndex, ExceptionResource.ArgumentOutOfRange_Index);
}
if ((count < 0) || (startIndex > (this._size - count)))
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.ArgumentOutOfRange_Count);
}
if (match == null)
{
ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
}
int num = startIndex + count;
for (int i = startIndex; i < num; i++)
{
if (match(this._items[i]))
{
return i;
}
}
return -1;
}


以后这类简单东西自己去看源代码吧,在csdn上提问不如自己去研究。
flyerwing 2010-02-09
  • 打赏
  • 举报
回复
int IndexOf(T item);
根据对象确定索引值
yyz985 2010-02-09
  • 打赏
  • 举报
回复
int IndexOf(T item);

111,120

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧