简体   繁体   中英

Cannot declare an extension method in a non-generic static class

I am trying to implement an extension for any c# object using extensions.

My method will use an object X that I cannot modify and takes the type of the object as an argument. Problem is I want to keep this object; I don't want it to be garbage-collected.

This is my current code, but I cannot declare an extension method in a non-generic static class ( Extensions_S<T> is NOT allowed. Compiler's error message is " extension method must be defined in a non-generic static class ").

namespace Lib
{
    public static class Extensions_S<T>
    {
        private static X generateA_X = null;
        public static A generateA<T>(this T value)
        {
            if (generateA_X == null)
                generateA_X = new X(typeof(T));

            return generateA_X.from(value);
        }
    }
}

generateA_X is a actually the equivalent of a static method variable. I want a different instance for each type T which calls this extension method. This is why I am trying to make Extensions_S generic.

My question is: Is there a workaround?

After trying to understand your problem i think I understood it, first the error is wrong, the error on the compiler complains because an extension must be created in a non-generic static class, and the text you posted seems to say the contrary.

So, if the problem is that each T must have a different X, you need to store the class once created and reused then you can use a non-generic class with a dictionary:

public static class Extensions_S
{
    static Dictionary<Type, X> generators = new Dictionary<Type, X>();

    public static A generateA<T>(this T value)
    {
        X generator;

        if(!generators.TryGetValue(typeof(T), out generator)
        {
            generator = new X(typeof(T));
            generators.Add(typeof(T), generator);
        }

        return generator.from(value);
    }
}
//public static class Extensions_S<T> { ...}
  public static class Extensions_S { ... }

Your generateA method can still be generic (like it already is) and you don't seem to use T anywhere else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM