문제

Is there a way to implement constraint type parameters where T is from a base class or if T is a list containing the "base class"?

Something looking like this :

public class SomeClass<T> where T : MyBaseClass, IList<MyBaseClass>
도움이 되었습니까?

해결책

No, you can't create generic constraint to work like OR.

And just to point that that kind of constraint would have been useless: you would not be able to use neither methods defined in BaseClass nor these from IList (because T could have been the first or the second).

다른 팁

No but you could have overloaded methods that take one or the other:

public class SomeClass<T> where T : MyBaseClass
{
    public void Process(T instance)
    {
    }

    public void Process(IList<T> list)
    {
    }
}

Why don't you implement an interface on the BaseClass and do.

public class SomeClass<T> where T : class, IBaseInterface

This also guarantees that the children are implementing the appropriate contracts that you want to expose.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top