1

我正在尝试使用 LINQ,但我不断收到此错误消息:

运算符“<”不能应用于“Ilistprac.Location”和“int”类型的操作数

我尝试了覆盖,但收到一条错误消息:

'Ilistprac.Location.ToInt()':找不到合适的方法来覆盖

所有的 IList 接口也是用 IEnurmerable 实现的(除非有人希望我在此列出)。

class IList2
{
    static void Main(string[] args)
    {

     Locations test = new Locations();
     Location loc = new Location();
     test.Add2(5);
     test.Add2(6);
     test.Add2(1);
     var lownumes = from n in test where (n < 2) select n;


     }
 }

public class Location
{
    public Location()
    {

    }
    private int _testnumber = 0;
    public int testNumber
    {
        get { return _testnumber; }
        set { _testnumber = value;}
    }

public class Locations : IList<Location>
{
    List<Location> _locs = new List<Location>();

    public Locations() { }

  public void Add2(int number)
    {
        Location loc2 = new Location();
        loc2.testNumber = number;
        _locs.Add(loc2);
    }

 }
4

4 回答 4

3

您可能想将 n.testNumber 与 2 进行比较

var lownumes = from n in test where (n.testNumber < 2) select n;

编辑:如果您想重载运算符,请查看本教程:

http://msdn.microsoft.com/en-us/library/aa288467%28v=vs.71%29.aspx

于 2012-04-13T19:03:31.180 回答
1

尝试

var lownumes = from n in test where (n.testNumber < 2) select n;
于 2012-04-13T19:04:47.233 回答
1

您要么想要比较n.testNumber,要么需要重载类<中的运算符,Location以便实际将其与int.

public class Location
{
    public Location()
    {

    }

    private int _testnumber = 0;
    public int testNumber
    {
        get { return _testnumber; }
        set { _testnumber = value;}
    }

    public static bool operator <(Location x, int y) 
    {
        return x.testNumber < y;
    }

    public static bool operator >(Location x, int y) 
    {
        return x.testNumber > y;
    }
 }
于 2012-04-13T19:07:40.007 回答
0

另一种选择是在 Location 类上创建一个隐式转换运算符,如下所示:

public class Location
{
    // ...
    public static implicit operator int(Location loc)
    {
        if (loc == null) throw new ArgumentNullException("loc");
        return loc.testNumber;
    }
}

Location有了上面的内容,编译器将在将实例与 int 进行比较时尝试在实例上调用此转换运算符。

于 2012-04-13T20:44:47.433 回答