Created
February 11, 2013 19:17
-
-
Save daanl/4756825 to your computer and use it in GitHub Desktop.
Dynamic translation service
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.Collections.Generic; | |
using System.Diagnostics.CodeAnalysis; | |
using System.Dynamic; | |
using System.Linq; | |
using System.Linq.Expressions; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace ConsoleApplication5 | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var translations = new List<Translation> | |
{ | |
new Translation | |
{ | |
Code = "EnterName", | |
Text = "Enter name please" | |
} | |
}; | |
var translationService = new TranslationService(translations); | |
string test = translationService.Translate.EnterName; | |
Console.WriteLine(test); | |
Console.ReadLine(); | |
} | |
} | |
public class TranslationService | |
{ | |
private readonly IEnumerable<Translation> _translations; | |
public TranslationService( | |
IEnumerable<Translation> translations | |
) | |
{ | |
_translations = translations; | |
} | |
public dynamic Translate | |
{ | |
get { | |
return new DynamicTranslatableObject( | |
code => | |
{ | |
var result = _translations.FirstOrDefault(x => x.Code.Equals(code, StringComparison.InvariantCultureIgnoreCase)); | |
return result == null ? code : result.Text; | |
} | |
); | |
} | |
} | |
private class DynamicTranslatableObject : DynamicObject | |
{ | |
private readonly Func<string, string> _translationLookupFunction; | |
public DynamicTranslatableObject(Func<string, string> translationLookupFunction) | |
{ | |
_translationLookupFunction = translationLookupFunction; | |
} | |
public override bool TryGetMember(GetMemberBinder binder, out object result) | |
{ | |
result = _translationLookupFunction(binder.Name); | |
return true; | |
} | |
} | |
} | |
public class Translation | |
{ | |
public string Code { get; set; } | |
public string Text { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment