Override Extension Method

Suppose I have two classes.

public class A {...} 
public class B : A {...}

I want to achieve overriding the extension function for both types.

public static void HelperExtension(this A a) {...}
public static void HelperExtension(this B b) {...}

I know that they are not virtual functions or behave like them. However, I am really surprised at the compiler behavior in this case.

Is there a way to call a function of type B without resolving its type? Or any suggestions for automatic resolution?

+5
source share
3 answers

As you said, there is no way to just make the extension virtual.

, , , , - .

, :

public static void HelperExtension(this A a)
{
    B b = a as B;
    if(b != null)
       HelperExtension(b);
    else
       //the rest of the method.
}

Switch Dictionary<Type, Action<A>>, , , , .

- dynamic. , , A, ( ) , :

public static void HelperExtension(this A a)
{
    ExtenstionImplementation((dynamic)a);
}

private static void ExtenstionImplementation(A a){...}
private static void ExtenstionImplementation(B a){...}
private static void ExtenstionImplementation(C a){...}
+2

- , -.

- , , .

, , .


:

B ? - ?

. , , , .

LINQ IEnumerable<T>.

+5

. , (, IBase, Base Derived, IBase ).

public interface IBase {...}
public class Base : IBase {...}
public class Derived : Base {...}

, ext IBase. ext Base, Derived.

public class MyClass {
    // other stuff
    public IBase ext;
}

AddedMethod(), IBase , . , , :

public static class MyExtensions
{
    public static void AddedMethod(this IBase arg) {...}
    public static void AddedMethod(this Base arg) {...}
    public static void AddedMethod(this Derived arg) {...}
}

ext.AddedMethod() MyClass. : , (.. AddedMethod ( IBase arg)) ext. IBase, , , :

public static class MyExtensions
{
    // just one extension method
    public static void AddedMethod(this IBase arg){
        // get actual argument type
        Type itsType = arg.GetType();

        // select the proper inner method
        MethodInfo mi = typeof(MyExtensions).GetMethod("innerAddedMethod",
            BindingFlags.NonPublic | BindingFlags.Static,
            null,
            new Type[] { itsType },
            null);

        // invoke the selected method
        if (mi != null) {
            mi.Invoke(null, new object[] { arg });
        }
    }

    private static void innerAddedMethod(Base arg) {
        // code for Base type arg 
    }

    private static void innerAddedMethod(Derived arg) {
        // code for Derived type arg
    }

Derived2 IBase, MyExtensions innerAddedMethod(), Derived2 .

0

All Articles