Overriding LINQ extension methods

2019-05-02 00:38发布

问题:

Is there a way to override extension methods (provide a better implementation), without explicitly having to cast to them? I'm implementing a data type that is able to handle certain operations more efficiently than the default extension methods, but I'd like to keep the generality of IEnumerable. That way any IEnumerable can be passed, but when my class is passed in, it should be more efficient.

As a toy example, consider the following:

// Compile: dmcs -out:test.exe test.cs

using System;

namespace Test {
    public interface IBoat {
        void Float ();
    }

    public class NiceBoat : IBoat {
        public void Float () {
            Console.WriteLine ("NiceBoat floating!");
        }
    }

    public class NicerBoat : IBoat {
        public void Float () {
            Console.WriteLine ("NicerBoat floating!");
        }

        public void BlowHorn () {
            Console.WriteLine ("NicerBoat: TOOOOOT!");
        }
    }

    public static class BoatExtensions {
        public static void BlowHorn (this IBoat boat) {
            Console.WriteLine ("Patched on horn for {0}: TWEET", boat.GetType().Name);
        }
    }

    public class TestApp {
        static void Main (string [] args) {
            IBoat niceboat = new NiceBoat ();
            IBoat nicerboat = new NicerBoat ();

            Console.WriteLine ("## Both should float:");
            niceboat.Float ();
            nicerboat.Float ();
            // Output:
            //      NiceBoat floating!
            //      NicerBoat floating!

            Console.WriteLine ();
            Console.WriteLine ("## One has an awesome horn:");
            niceboat.BlowHorn ();
            nicerboat.BlowHorn ();
            // Output:
            //      Patched on horn for NiceBoat: TWEET
            //      Patched on horn for NicerBoat: TWEET

            Console.WriteLine ();
            Console.WriteLine ("## That didn't work, but it does when we cast:");
            (niceboat as NiceBoat).BlowHorn ();
            (nicerboat as NicerBoat).BlowHorn ();
            // Output:
            //      Patched on horn for NiceBoat: TWEET
            //      NicerBoat: TOOOOOT!

            Console.WriteLine ();
            Console.WriteLine ("## Problem is: I don't always know the type of the objects.");
            Console.WriteLine ("## How can I make it use the class objects when the are");
            Console.WriteLine ("## implemented and extension methods when they are not,");
            Console.WriteLine ("## without having to explicitely cast?");
        }
    }
}

Is there a way to get the behavior from the second case, without explict casting? Can this problem be avoided?

回答1:

Extension methods are static methods, and you can't override a static method. Nor can you "override" an actual instance method with a static/extension method.

You'll have to use your optimized extension explicitly. Or implicitly by referencing your own extension's namespace instead of System.Linq.

Or explicitly check the type in your extension and call the correct one based on the runtime type.

This seems like a problem better suited for inheritance than extension methods. If you want different functionality based on the runtime type, then make the base method virtual and override it in the derived classes.

I see a lot of confusion over this aspect of extension methods. You have to understand that they aren't mixins, they don't actually get injected into the class. They're just syntactic sugar that the compiler recognizes and "allows" you to execute it as if it were a regular instance method. Imagine that it wasn't an extension method, just a static method instead:

public static void BlowHorn (IBoat boat) {
    Console.WriteLine ("Patched on horn for {0}: TWEET", boat.GetType().Name);
}

How would you "override" this method from the IBoat implementation? You can't. The only thing you can do is put type checking into this static method, or write some dynamic method invocation code, either using a dynamic block in C# 4 or Reflection in earlier versions.

To make this even clearer, have a look at this code from the System.Linq.Enumerable class out of Reflector:

public static TSource ElementAt<TSource>(this IEnumerable<TSource> source, 
    int index)
{
    TSource current;
    if (source == null)
    {
        throw Error.ArgumentNull("source");
    }
        IList<TSource> list = source as IList<TSource>;
    if (list != null)
    {
        return list[index];
    }
// ...
}

This is one of the core extension methods in the .NET Framework. It allows optimization by explicitly checking if the parameter implements IList<T>. Other than this, it has no way of knowing whether or not the underlying concrete type actually supports indexed access. You'd have to do it this same way; create another interface like IHorn or something, and in your extension, check whether or not the IBoat also implements IHorn, same as the Enumerable class does here.

If you don't control the code for either the IBoat classes or the extension methods, then you're out of luck. If you do, then use multiple-interface inheritance, explicit type checking, or dynamic code, those are your options.