Skip to content
Permalink
Browse files

Game - Verb.Register using reflection

  • Loading branch information...
bobbymcr committed Dec 19, 2018
1 parent dcd68c6 commit 42bdc834bbf25179a2bd2816398d62f04f61dfec
Showing with 25 additions and 15 deletions.
  1. +1 −9 sample/src/Game.cs
  2. +24 −6 sample/src/Verb.cs
@@ -33,16 +33,8 @@ public void Run(TextReader reader, TextWriter writer)
private static Words InitializeWords()
{
Words w = new Words();
w.Add(Verb.Drop, "throw");
w.Add(Verb.Go);
w.Add(Verb.Greet, "hello", "hi");
w.Add(Verb.Look);
w.Add(Verb.Move);
w.Add(Verb.Quit, "exit");
w.Add(Verb.Read);
w.Add(Verb.Take, "get");
w.Add(Verb.Inventory, "inv");

Verb.Register(w);
Noun.Register(w);

return w;
@@ -4,25 +4,43 @@

namespace Adventure.Sample
{
using System.Reflection;

internal sealed class Verb
{
public static readonly Verb Drop = new Verb("drop");
public static readonly Verb Drop = new Verb("drop", "throw");
public static readonly Verb Go = new Verb("go");
public static readonly Verb Greet = new Verb("greet");
public static readonly Verb Inventory = new Verb("inventory");
public static readonly Verb Greet = new Verb("greet", "hello", "hi");
public static readonly Verb Inventory = new Verb("inventory", "inv");
public static readonly Verb Look = new Verb("look");
public static readonly Verb Move = new Verb("move");
public static readonly Verb Take = new Verb("take");
public static readonly Verb Quit = new Verb("quit");
public static readonly Verb Take = new Verb("take", "get");
public static readonly Verb Quit = new Verb("quit", "exit");
public static readonly Verb Read = new Verb("read");

private readonly string verb;
private readonly string[] synonyms;

private Verb(string verb)
private Verb(string verb, params string[] synonyms)
{
this.verb = verb;
this.synonyms = synonyms;
}

public static implicit operator string(Verb v) => v.verb;

public static void Register(Words words)
{
foreach (FieldInfo fi in typeof(Verb).GetFields(BindingFlags.Static | BindingFlags.Public))
{
Verb v = (Verb)fi.GetValue(null);
v.AddTo(words);
}
}

private void AddTo(Words words)
{
words.Add(this.verb, this.synonyms);
}
}
}

0 comments on commit 42bdc83

Please sign in to comment.
You can’t perform that action at this time.