-
-
Save Rohansi/1022dd18b5a0bb16d60b to your computer and use it in GitHub Desktop.
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 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