Upcast for the general type

I have the following class hierarchy:

class A {
 /// stuff
}

class B : A {
 /// stuff
}

class C<T> : B {
  /// stuff
}

Then somewhere completely different, I have the following three methods:

public void foo(A a) {
}

// overload 1
public void bar(B b) {
}

// overload 2
public void bar<T>(C<T> ct) {
}

Now for some reason I need to call the "right" panel from foo, given the actual type A. That is, if A really belongs to type B, I need to call overload 1, and if A is really type C (whatever T ), I need to call overload 2. And for completeness, if A is neither B nor C, do nothing.

I am currently using the IsAssignableFrom method of the Type class to decide if conversion to B is possible:

public void foo(A a) {
   if (typeof(B).IsAssignableFrom(a)) {
      bar((B)a);
   }
}

But this also applies to options C. So, the question is, how can I complete this survey? Reflection? dynamics? We use .NET 4, so everything that was introduced in C # 5, I can not use.

+2
2

dynamic. , , , .

bar((dynamic)value);
+3

- , :

. "- ". bar A foo .

- .

interface IVisitor
{
    void Visit(B b);
    void Visit<T>(C<T> c);
}
class A 
{
    public virtual void Accept(IVisitor v)
    { } // Do nothing
}
class B : A
{
    public override void Accept(IVisitor v)
    { v.Visit(this); }
}
class C<T> : B 
{
    public override void Accept(IVisitor v)
    { v.Visit<T>(this); }
}
class P
{
    class Visitor : IVisitor
    {
        public void Visit(B b) { bar(b); }
        public void Visit<T>(C<T> c) { bar<T>(c); }
    }
    public static bar(B b) { }
    public static bar<T>(C<T> c) { }
    public static void foo(A a)
    {
        a.Accept(new Visitor());
    }
}

, A, B C<T>.

- "" foo, A. , A B, 1, A C ( T), 2. , A B, C, .

:

public void foo(A a) 
{
    if (a is B) bar((B)a);

; , if (a is C<?>) bar((C<?>)a;.

dynamic. , dynamic bar , , .

+6

Source: https://habr.com/ru/post/1524707/


All Articles