Java -> C# Creating Anonymous Instance of Abstract Class

前端 未结 1 1639
名媛妹妹
名媛妹妹 2021-01-26 23:59

for training purposes I am following along a Tutorial written for Java, which I successfully \'translated\' into C# so far, however, I am facing now a problem for which I don\'t

相关标签:
1条回答
  • 2021-01-27 00:00

    There are no anonymous classes in C#, but you have two ways of achieving the same result:

    • Make private, nested, named classes, and reference them in the array initializer, or
    • Make a constructor take a delegate for each abstract method that you plan to override.

    The first approach is self-explanatory, but the code would be quite a bit longer. The named classes should be OK, because they are private to the implementation of your publicly visible class.

    The second approach could look as follows:

    public class LevelUpOption {
      private String name;
      public String name() { return name; }
    
      public LevelUpOption(String name, Action<Creature> invoke){
        this.name = name;
        this.invoke = invoke;
      }
    
      public readonly Action<Creature> invoke;
    }
    

    Now you can initialize your array like this:

    private static LevelUpOption[] options = new [] {
        new LevelUpOption("Increased hit points", c => c.gainMaxHp() ),
        new LevelUpOption("Increased attack value", c => c.gainAttackValue()),
        ...
    };
    

    Since invoke is a delegate, the syntax of calling it is the same:

    options[i].invoke(myCreature);
    
    0 讨论(0)
提交回复
热议问题