Created
September 15, 2011 02:34
-
-
Save dylanmei/1218387 to your computer and use it in GitHub Desktop.
Dynamic Resource magic
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 Program | |
{ | |
static void Main() | |
{ | |
var view = new View(); | |
System.Console.WriteLine(view.Resources.A.B.Value); | |
System.Console.WriteLine(view.Resources.A.B.Blah); | |
System.Console.ReadLine(); | |
} | |
} | |
public class View | |
{ | |
public dynamic Resources = new ResourceFinder(new ResourceHelper()); | |
} | |
public interface IResourceHelper | |
{ | |
string GetString(string resourceName); | |
bool CanLocateResource(string resourceName); | |
} | |
public class ResourceFinder : DynamicObject | |
{ | |
string name; | |
readonly ResourceFinder root; | |
readonly ResourceFinder parent; | |
readonly IResourceHelper helper; | |
public ResourceFinder(IResourceHelper helper) | |
{ | |
root = this; | |
this.helper = helper; | |
} | |
ResourceFinder(ResourceFinder parent) | |
{ | |
root = parent.root; | |
helper = root.helper; | |
this.parent = parent; | |
} | |
internal string Path() | |
{ | |
var path = name; | |
var node = parent; | |
while (node != null) | |
{ | |
path = string.Concat(node.name, ".", path); | |
node = node.parent; | |
} | |
return path; | |
} | |
internal bool Exists() | |
{ | |
return helper.CanLocateResource(Path()); | |
} | |
internal ResourceFinder Next() | |
{ | |
return new ResourceFinder(this); | |
} | |
object Value() | |
{ | |
return helper.GetString(Path()); | |
} | |
public override bool TryGetMember(GetMemberBinder binder, out object result) | |
{ | |
name = binder.Name; | |
result = Exists() ? Value() : Next(); | |
return true; | |
} | |
public override string ToString() | |
{ | |
return parent == null ? "" : parent.Path(); | |
} | |
} | |
class ResourceHelper : IResourceHelper | |
{ | |
public string GetString(string resourceName) { | |
return CanLocateResource(resourceName) ? "HELLO!" : null; | |
} | |
public bool CanLocateResource(string resourceName) { | |
return resourceName == "A.B.Value"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment