简体   繁体   中英

How can i make a generic function of two functions with a generic type specifier to a parameter

Sorry if my question is poorly worded, but it is precisely because I don't know how to word the question that I can't easily search this on google.

Basically I just want to combine these two functions but couldn't find a generic example with a generic inside the of a parameter? What do I call the bracketed area of a parameter? is type specifier a real term?

anyway I want to combine them into one function that takes two keyvaluepair<int, T> but I can't seem to get the syntax right.

public class BinarySearchComparers:IComparer<KeyValuePair<int, string>>, IComparer<KeyValuePair<int, byte>>
  {
    public int Compare(KeyValuePair<int, string> x, KeyValuePair<int, string> y)
    {
      return x.Key.CompareTo(y.Key); 
    }
    public int Compare(KeyValuePair<int, byte> x, KeyValuePair<int, byte> y)
    {
      return x.Key.CompareTo(y.Key);
    }
  }
public class BinarySearchComparers<T> : IComparer<KeyValuePair<int, T>>  // Declares a generic type
{
    public int Compare(KeyValuePair<int, T> x, KeyValuePair<int, T> y)
    {
        return x.Key.CompareTo(y.Key); 
    }
}

Is it what you want?

Update

Given Chris Sinclair understanding of your question, the solution might be:

public class BinarySearchComparers<U, T> : IComparer<KeyValuePair<U, T>>  // Declares a generic type
    where U : IComparable<U>  // Restricts the type U to implémentations of IComparable<U> (necessary to call CompareTo)
{
    public int Compare(KeyValuePair<U, T> x, KeyValuePair<U, T> y)
    {
        return x.Key.CompareTo(y.Key); 
    }
}

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