سؤال

I basically want to inject an extension method to each copy of ArrayList, which would perform the following behavior:

ArrayList ourList = new ArrayList();
ourList.Add(randomarray or random arraylist);

It'd add the CONTENT of the given array, arraylist or stack to 'ourList' and not the array, arraylist or stack itself.

However, my problem is:

How do I inject an extension method ONLY into the instanced class? The following code adds the method to the ArrayList baseclass and any instanced copy, however I want it to be ONLY available when you access an instanced copy of the class.

    public static void Add(this ArrayList ourlist){

    }

    ArrayList.Add(); // Works, but shouldn't
    ArrayList result = new ArrayList();
    result.Add(); // Works

So, how do I manage this?

هل كانت مفيدة؟

المحلول

How do I inject an extension method ONLY into the instanced class?

If you're talking about adding an extension method to individual instances, you can't. There's no such concept in C#. An extension method "extends" the type, not individual instances of the type. How would you expect the compiler to know which instances had the extension applied to it at compile-time, if that knowledge is only available at execution-time?

If you're talking about calling an extension method like any other static method, that will always be feasible, and can't be prevented. So you could always call:

MyExtensionClass.Add(null, null);

If you're not talking about either of those things, it's not clear what you mean - but making a static call to ArrayList.Add as shown in your sample code really won't compile. Are you sure you haven't got a variable called ArrayList? (That would certainly mess things up.)

Furthermore, as ArrayList already has an Add(object) instance method, your new extension method would never be used anyway. (You should really move away from the non-generic collections as quickly as you can.)

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top