c# - Concise, fast singleton subclasses -


i'm writing, in c#, interpreter dynamic language, , implementing primitive functions abstract class primitive virtual apply method, each actual primitive function subclass overrides apply.

(an alternative have class primitive , store function pointer apply. however, making virtual method seems faster, , code run frequently, small speedup worth having.)

obviously go ahead , create full-blown class file each primitive function, can't feeling there ought more concise way of doing things creating dozens of tiny class files.

in java i'd use anonymous subclass syntax create , instantiate subclass in 1 expression, don't think c# has exact counterpart.

what best way of doing in c#?

firstly, wouldn't assume virtual method call faster delegate. maybe will, maybe won't - if performance really important you, should measure that. simple code using lambda expressions, particularly if all you're trying represent function:

public static readonly func<int, int> addition = (x, y) => x + y; public static readonly func<int, int> subtraction = (x, y) => x - y; // etc 

(i'm guessing @ sorts of operation here, don't know details.)

there's no particularly tiny syntax subclasses in c#, semi-singletons find nested classes work well... similar java enums:

public abstract class primitive {     public static readonly primitive addition = new additionprimitive();     public static readonly primitive subtraction = new subtractionprimitive();      // prevent outside instantiation     private primitive()     {     }      public abstract int apply(int x, int y);      // else want      private class additionprimitive : primitive     {         public override int apply(int x, int y)         {             return x + y;         }     }      private class subtractionprimitive : primitive     {         public override int apply(int x, int y)         {             return x - y;         }     } } 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

qt - Errors in generated MOC files for QT5 from cmake -