Entering polymorphic values ​​with multiple interfaces in C #

Is there any time-safe option for checking compile time with reference to values ​​that implement multiple interfaces?

Considering

interface A {
    void DoA();
}

interface B {
    void DoB();
}

I can write code for objects that implement A either B , but not both. So I have to come up with ugly wrappers:

class ABCollection {
    private class ABWrapper : A, B {
        private readonly A a;
        private readonly B b;

        public static ABWrapper Create<T>(T x) where T : A, B {
            return new ABWrapper { a = x, b = x };
        }

        public void DoA() {
            a.DoA();
        }

        public void DoB() {
            b.DoB();
        }
    }

    private List<ABWrapper> data = new List<ABWrapper>();

    public void Add<T>(T val) where T : A, B {
        data.Add(ABWrapper.Create(val));
    }
}

Is there a trick to writing this code more intuitively without losing security type (runtime-casts, etc.)?

eg.

private List<A and B> ...

Change . It’s not about having a list in particular - I just wanted to give a “complete” example with the problem of storing such values. My problem is simply how to introduce a combination of both interfaces (e.g., A & Bor A and B).

Another useful example: List<IDrawable & IMovable>...

+5
3

, #, . , :

void Foo<T>(T t) where T : IFoo, IBar
{
  t.Foo();
  t.Bar();
}

, IFoo, IBar.

void Foo(IFoo-and-IBar t) 
{
  t.Foo();
  t.Bar();
}

, IFoo, IBar. , .

+6

, , IFoo-and-IBar, .

-, . ( ), :

public abstract class ABWrapper : IA, IB
{
    private readonly IA a;
    private readonly IB b;

    protected ABWrapper( IA a, IB b ) { this.a = a; this.b = b; }

    // Implement methods on IA and IB
}

public sealed class ABWrapper<T> : ABWrapper
    where T : IA, IB
{
    private ABWrapper( T a, T b ) : base( a, b ) { }

    public static implicit operator ABWrapper<T>( T t )
    {
        if ( t == null ) return null;
        return new ABWrapper<T>( t, t );
    }
}

public class AB : IA, IB { }

void Method( ABWrapper x )
{
}

void Main()
{
    AB x = null;
    Method( (ABWrapper<AB>) x );
}

, ABWrapper<T> . ABWrapper ToABWrapper<T>(this T t) where T : IA, IB , .

, , AB ABWrapper ABWrapper<T>. , , .

ABWrapper .

+1

, . , :

interface AorB {}

interface A : AorB {
    void DoA();
}

interface B : AorB {
    void DoB();
}

. , ( ).

It seems to me that this is a possible violation of SRP, and the collection does too much. Otherwise, the interfaces are too fine-grained.

0
source

All Articles