1

LINQ を使用しようとしていますが、次のエラー メッセージが表示され続けます。

演算子 '<' は、型 'Ilistprac.Location' および 'int' のオペランドには適用できません

オーバーライドを試みましたが、エラー メッセージが表示されます。

'Ilistprac.Location.ToInt()': オーバーライドする適切なメソッドが見つかりません

すべての IList インターフェイスも IEnumerable で実装されています (誰かが私に望んでいない限り、ここにはリストされていません)。

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

比較するか、クラスで演算子n.testNumberをオーバーロードする必要があるため、実際に.<Locationint

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 に答える
1

試す

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

もう 1 つの方法は、次のように 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 に答える