Skip to content

Instantly share code, notes, and snippets.

@WilliamBundy
Created June 1, 2015 03:53
Show Gist options
  • Save WilliamBundy/262582915f719bb4dba1 to your computer and use it in GitHub Desktop.
Save WilliamBundy/262582915f719bb4dba1 to your computer and use it in GitHub Desktop.
Playing around with a more dynamic/JS style in C#
class Bunch : IEnumerable
{
public object this [string name]
{
get
{
try
{
return this.GetType().GetField(name).GetValue(this);
}
catch(Exception)
{
Console.WriteLine("Attempted to access non-existent property on {0}: {1}", this.GetType().Name, name);
return null;
}
}
set
{
try
{
this.GetType().GetField(name).SetValue(this, value);
}
catch(Exception)
{
Console.WriteLine("Attempted to set non-existent property on {0}: {1}", this.GetType().Name, name);
}
}
}
public Type Filter;
public IEnumerator GetEnumerator()
{
var fields = this.GetType().GetFields().Where((FieldInfo f) => { return Filter != null ? f.FieldType == Filter: true; });
//I'm being lazy
var names = new List<string>(this.GetType().GetFields().Length); // it can't be longer than that!
foreach(var field in fields)
{
if(field.Name != "Filter")
names.Add(field.Name);
}
return (IEnumerator)names.GetEnumerator();
}
}
class Character: Bunch
{
public string Name;
public int Level;
public int MaxHp { get { return Level + Const * 2 + 1; } }
public int CurrentHp;
public int Strength;
public int Wisdom;
public int Dex;
public int Const;
public Character()
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment