Last active
May 10, 2016 16:26
-
-
Save thinkingserious/237e370ee747f5b8403650f0c794617e to your computer and use it in GitHub Desktop.
Fluent Interface in C# Using Method Chaining and Reflection
This file contains hidden or 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
using System; | |
using System.Dynamic; | |
namespace Fluent | |
{ | |
class Client : DynamicObject | |
{ | |
public string UrlPath; | |
public Client(string urlPath = null) | |
{ | |
UrlPath = (urlPath != null) ? urlPath : null; | |
} | |
private Client BuildClient(string name = null) | |
{ | |
string endpoint; | |
if (name != null) | |
{ | |
endpoint = UrlPath + "/" + name; | |
} | |
else | |
{ | |
endpoint = UrlPath; | |
} | |
UrlPath = null; // Reset the current object's state before we return a new one | |
return new Client(endpoint); | |
} | |
public Client _(string name) | |
{ | |
return BuildClient(name); | |
} | |
public override bool TryGetMember(GetMemberBinder binder, out object result) | |
{ | |
result = BuildClient(binder.Name); | |
return true; | |
} | |
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) | |
{ | |
result = UrlPath; | |
return true; | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
dynamic client = new Client(); | |
dynamic chain = client.hello.world; | |
Console.WriteLine(chain.UrlPath); | |
Console.ReadLine(); | |
dynamic new_chain = chain.thanks._("for").all.the.fish; | |
Console.WriteLine(new_chain.method()); | |
Console.ReadLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment