简体   繁体   中英

force generic parameter two implement one of two interfaces c#

Is there anyway to force a constraints for a generic definition to implement one interface of two when I can not touch both interface

I want to do it for the IComparable interface:

class A<T> where T :IComparable IComparable<T>

I do not want the T must implements both interface but on of them

Is there any way to do it when I can not change the IComparable?

You could use one interface and wrap the other.

class A<T> where T : IComparable
{
}

class ComparableWrapper<T> : IComparable
      where T : IComparable<T>
{
    T _obj;
    public ComparableWrapper(T obj)
    {
        _obj = obj;
    }

    public T WrappedObject {get { return _obj;}}

    // wrapping code
}

This way, you can use both IComparable and IComparable

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