Created
June 1, 2015 03:53
-
-
Save WilliamBundy/262582915f719bb4dba1 to your computer and use it in GitHub Desktop.
Playing around with a more dynamic/JS style in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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