Skip to content

Instantly share code, notes, and snippets.

@Rohansi
Created January 7, 2015 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Rohansi/1022dd18b5a0bb16d60b to your computer and use it in GitHub Desktop.
Save Rohansi/1022dd18b5a0bb16d60b to your computer and use it in GitHub Desktop.
class Person
{
public string Name { get; set; }
}
class ViewModel
{
public Person Person;
}
class Program
{
static void Main(string[] args)
{
var viewModel = new ViewModel
{
Person = new Person
{
Name = "Rohan"
}
};
var selector = Make("Person.Name").Compile();
Console.WriteLine(selector.Invoke(viewModel));
}
static Expression<Func<object, object>> Make(string path)
{
var pathParts = path.Split('.');
Func<object, object> func = viewModel =>
{
var current = viewModel;
foreach (var property in pathParts)
{
var currentType = current.GetType();
var propertyInfo = currentType.GetProperty(property);
if (propertyInfo != null)
{
current = propertyInfo.GetValue(current);
continue;
}
var fieldInfo = currentType.GetField(property);
if (fieldInfo != null)
{
current = fieldInfo.GetValue(current);
continue;
}
throw new Exception();
}
return current;
};
var viewModelParam = Expression.Parameter(typeof(object));
var callParams = new Expression[]
{
viewModelParam
};
var funcInstance = Expression.Constant(func.Target);
var callExpr = Expression.Call(funcInstance, func.Method, callParams);
return Expression.Lambda<Func<object, object>>(callExpr, viewModelParam);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment