Skip to content

Instantly share code, notes, and snippets.

@daanl
Created February 11, 2013 19:17
Show Gist options
  • Save daanl/4756825 to your computer and use it in GitHub Desktop.
Save daanl/4756825 to your computer and use it in GitHub Desktop.
Dynamic translation service
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