简体   繁体   中英

Generic method that further constrains the class type parameter

I have a data structure with a BisectLeft method

public class MyStruct<T> where T: IComparable<T>
{
    public T BisectLeft(T item) {...}
}

I would like to add an overload of BisectLeft for a generic type U where T: IComparable<U>

    public T BisectLeft(T item) {...}

    public T BisectLeft<U>(U item) where T: IComparable<U> {...}

This doesn't compile because it cannot resolve the type T . I also cannot add T as BisectLeft<T, U> because T would be considered a duplicate of the type parameter of the class MyStruct<T> .

Is there anyway to achieve this without adding U as a type parameter of the class?

You should specify your type parameter like where T either at the parent type, or at the methods. It won't work if you define it at both places.

In your case, you should do it only at the methods, like:

public class MyStruct
{
    public T BisectLeft<T>(T item)
        where T : IComparable<T>
    {
        return ...;
    }

    public T BisectLeft<T, U>(U item)
        where T : IComparable<U>
    {
        return ...;
    }
}

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