Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save bozhink/e812e8efea30dc8d89160498e8c19735 to your computer and use it in GitHub Desktop.
Save bozhink/e812e8efea30dc8d89160498e8c19735 to your computer and use it in GitHub Desktop.
namespace ExpressionTest
{
using System;
using System.Linq.Expressions;
public static class Program
{
public static void Main(string[] args)
{
string str = "Test";
Console.WriteLine("{0} : {1}", GetName(() => str.Length), str.Length);
// Prints Length : 4
PrintProperty(() => str.Length);
var foo = new Foo
{
Bar = "1"
};
PrintProperty<Foo, string>(f => f.Bar);
foo.Set(f => f.Bar, "c")
.Set(f => f.Baz, 1)
.Set(f => f.Bar, "1");
var builder = new SetBuilder<Foo>(foo);
builder.Set(f => f.Bar, "2").Set(f => f.Baz, 4);
Console.WriteLine(foo.Bar);
Console.WriteLine(foo.Baz);
Console.ReadKey();
}
public static string GetName<T>(Expression<Func<T>> e)
{
var member = (MemberExpression)e.Body;
return member.Member.Name;
}
public static void PrintProperty<T>(Expression<Func<T>> e)
{
var member = (MemberExpression)e.Body;
string propertyName = member.Member.Name;
T value = e.Compile()();
Console.WriteLine("{0} : {1}", propertyName, value);
}
public static void PrintProperty<TObject, TField>(Expression<Func<TObject, TField>> e)
{
var member = (MemberExpression)e.Body;
string propertyName = member.Member.Name;
Console.WriteLine(propertyName);
}
public static T Set<T, TProperty>(this T o, Expression<Func<T, TProperty>> e, TProperty value)
where T : class
{
var member = (MemberExpression)e.Body;
string propertyName = member.Member.Name;
var type = typeof(T);
var property = type.GetProperty(propertyName);
var method = property.SetMethod;
method.Invoke(o, new object[] { value });
return o;
}
private class Foo
{
public string Bar { get; set; }
public int Baz { get; set; }
}
public class SetBuilder<T>
where T : class
{
private readonly T item;
public SetBuilder(T item)
{
if (item == null)
{
throw new ArgumentNullException(nameof(item));
}
this.item = item;
}
public T Object => this.item;
public SetBuilder<T> Set<TProperty>(Expression<Func<T, TProperty>> e, TProperty value)
{
var member = (MemberExpression)e.Body;
string propertyName = member.Member.Name;
var type = typeof(T);
var property = type.GetProperty(propertyName);
var method = property.SetMethod;
method.Invoke(this.item, new object[] { value });
return this;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment