简体   繁体   中英

Trouble implementing IComparable<T> in C#

I'm trying to sort an array in Unity by name, using Array.Sort() .

I've been reading as much as I can but still can't adapt it into my little project here. Here is what I have so far:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;

public class UIController : MonoBehaviour, IComparable<Slot>
{
    public static UIController instance;
    public Text uiMessageBox;
    public Slot[] slots;

    private void Awake()
    {
        if (instance == null)
            instance = this;
        else
            Destroy(this);

        DontDestroyOnLoad(this);

        slots = FindObjectsOfType<Slot>();
        Array.Sort(slots, ); // HELP: NOT SURE WHAT TO PUT HERE
    }

    public int CompareTo(Slot other)
    {
        return this.name.CompareTo(other.name);
    }
}

Note, I deleted the parts I think are irrelevant in this class (such as the code that displays a message string on screen etc).

ALSO NOTE: I implement here IComparable<Slot> but I also tried it with IComparable<UIController> . (like I say, I've seen lots of examples here and other websites, but cannot quite get it to work in my code.)

Why not use delegate form?

Array.Sort(slots, (slot1, slot2) => slot1.name.CompareTo(slot2.name));

If you still want to implement the IComparable interface, you must write it inside the Slot class.

And you can also implement IComparer interface in any class.

class AnyClass : IComparer<Slot>
{
    public int Compare(Slot slot1, Slot slot2)
    {
        return slot1.name.CompareTo(slot2.name);
    }
}

I was able to keep the code within my UIController class which is how I imagined it would be (since I built the array of slots there , it felt right for me to sort it there also.)

Here's how its done:

public class UIController : MonoBehaviour, IComparer<Slot>
{
public static UIController instance;
public Text uiMessageBox;
public Slot[] slots;


private void Awake()
{

    slots = FindObjectsOfType<Slot>();
    Array.Sort(slots, this); // i just passed 'this' as the IComparer parameter :)

}

public int Compare(Slot x, Slot y)
{
   return x.name.CompareTo(y.name);
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM