C# - 将对象参数传递给list.Find函数

时间:2015-09-21 10:42:48

标签: c#

我正在为列表编写一个Find函数,该列表要求我将Object作为参数传入。原因是Find函数使用当前聚焦对象(CFO)中的一些变量来查找下一个对象(X和Y坐标)。

Find函数在框区域中查找它可以找到的第一个对象,使用当前聚焦的Object的X,Y来创建框区域。我遇到的问题是我无法弄清楚如何将对象作为Find函数的参数传递。

有没有人有解决方案?我似乎无法在Stackoverflow或Google上找到任何内容。

3 个答案:

答案 0 :(得分:0)

我不确定我是否理解你的问题但我会试一试,也许我很幸运:

将Find-Method编写为通用,以便您可以在签名中使用带有接口的where子句。

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

namespace ObjectsWithCoordinates
{
    public interface IObjWithCoordinates
    {
        int X { get; set; }
        int Y { get; set; }
    }

    public class MyObjWithCoordinates : IObjWithCoordinates
    {
        public int X { get; set; }
        public int Y { get; set; }
        public string Name { get; set; }
    }


    public static class Extensions
    {
        public static T Find<T>(this IEnumerable<T> objects, int coordX, int coordY)
            where T : IObjWithCoordinates
        {
            if (objList == null)
                return;

            var objList = objects as IEnumerable<IObjWithCoordinates>;

            // Not needed, this is actually too defensive
            if (objList == null)
                throw new ArgumentException("objects must implement IObjWithCoordinates");

            return (T)objList.FirstOrDefault(o => o.X == coordX && o.Y == coordY);
        }
    }

    public static class Program
    {
        static void Main()
        {
            var obj1 = new MyObjWithCoordinates { X = 1, Y = 1, Name = "Name 1" };
            var obj2 = new MyObjWithCoordinates { X = 2, Y = 2, Name = "Name 2" };
            var obj3 = new MyObjWithCoordinates { X = 3, Y = 3, Name = "Name 3" };

            var coordObjList = new List<MyObjWithCoordinates> { obj1, obj2, obj3 };

            Console.WriteLine(coordObjList.Find(2, 2).Name);
            // Result: "Name 2"
            Console.ReadLine();
        }
    }
}
  

简短说明:

     

诀窍是静态扩展 - 将自身约束到的方法   使用您定义的接口的对象(其中T:接口)。这样你可以肯定   您列表中的任何类型的对象都可以通过X / Y进行搜索   属性。从那里,您可以在使用您的界面的任何通用List上调用Find-Method。

     

随着你的需要改变。

答案 1 :(得分:0)

您可以在传递给Find的谓词函数中使用该对象(在本例中为方框)。

Rectangle box = new Rectangle(2, 2, 10, 10);

List<Point> pointList = new List<Point>();
pointList.Add(new Point(0, 0));
pointList.Add(new Point(3, 3));
pointList.Add(new Point(5, 4));
pointList.Add(new Point(20, 20));

Predicate<Point> firstPointInBoxPredicate = (Point p) =>
{
    return box.Contains(p);
};

Point firstPoint = pointList.Find(firstPointInBoxPredicate); // firstPoint = x: 3, y: 3

答案 2 :(得分:0)

您的问题与(我认为)使用List<T>.Find方法以及在列表中搜索的自定义Find方法有很大的歧义。

我认为此代码可能会对您有所帮助:

public CustomObject Find(List<CustomObject> list, CustomObject cfo)
{
    return list.Find(item => IsWithinBoxOf(cfo, item));
}

private bool IsWithinBoxOf(CustomObject cfo, CustomObject item)
{
    // return whether the item is within the box of cfo.
    return item.X <= cfo.X + 1 && item.Y <= cfo.Y + 1;
}