具有实现IComparable的泛型类组合的类,C#

时间:2016-08-27 20:18:02

标签: c# generics interface icomparable

我想创建一个PQ,它使用一个名为Key的单独类来存储可以采用泛型类型的值,我还想将类型限制为string和int。我需要实现IComparable接口。我该怎么做呢?

我收到一些关于类型参数的错误,我在我的代码中添加了注释以显示错误的位置。

我该如何实现这样的目标?

public class MaxPQ<T>
{
    private Key[] pq; //Key requires 1 type argument
    private int N;

    public MaxPQ(int capacity)
    {
        pq = new Key[capacity + 1]; //Requires Type arguments
    }


    private void exch<T>(int i, int j)
    {
        Key<T> temp = pq[i]; //Cannot be used as a type
        pq[i] = pq[j];
        pq[j] = temp;
    }



    /// <summary>
    /// Key class for value in the Priority Queue
    /// </summary>
    private class Key<T> where T : IComparable<int, string> //IComparable cannot be used with type argument
    {
        T _value;

        public Key(T value)
        {
            _value = value;
        }


        public int CompareTo(Key obj) //Required type arguments
        {
            if (obj == null) return 1;

            return;
        }


    }

2 个答案:

答案 0 :(得分:0)

这是一种方法:

public class Key<T>
{
    public T Value { get; private set; }
    private Key( ) { }
    public static Key<T> Make(T inVal)
    {
        var inT = inVal.GetType();
        if (inT != typeof(int) && inT != typeof(string))
            throw new TypeAccessException("Wrong type");
        return new Key<T> {Value = inVal};
    }
}

使用它:

class Program
{
    static void Main(string[] args)
    {
        var myKey = Key<string>.Make("StringKeyValue");
        Console.WriteLine($"String Key is {myKey.Value}");
        var otherKey = Key<int>.Make(23);
        Console.WriteLine($"integer Key is {otherKey.Value}");
        try {var badTypKey = Key<DateTime>.Make(DateTime.Now); }
        catch (TypeAccessException x)
        { Console.WriteLine($" Got TypeAccessException {x.Message}"); }
        Console.WriteLine("Hit any key to terminate.");
        Console.ReadLine();
    }
}

答案 1 :(得分:0)

这会有用吗?

int dust
int candy
List<Float> pokemonlevels