Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can do some nice refactor-friendly things with LINQ Expressions. Here is a snippet of utilty code I used for such occasions. It allows you to get the Name, Type and Value of a <em>property</em> (it won't work with fields without modifications). There's also a setter for the value.</p> <pre><code>public static void Main(string[] args) { var test = new { Test1 = 42, Test2 = "123", Test3 = 3.14195 }; somethingSomething(test, t =&gt; t.Test1); somethingSomething(test, t =&gt; t.Test2); somethingSomething(test, t =&gt; t.Test3); } static void somethingSomething&lt;TObj,TProperty&gt;(TObj obj, Expression&lt;Func&lt;TObj,TProperty&gt;&gt; expr) { var accessor = GetMemberAccessor(expr, obj); String name = accessor.Name; TProperty value = accessor.Value; String typeName = accessor.Type.Name; Console.WriteLine("{0} = {1} ({2})", name, value, typeName); } </code></pre> <p>The output of that would be:</p> <pre><code>Test1 = 42 (Int32) Test2 = 123 (String) Test3 = 3.14195 (Double) </code></pre> <p>To make this work, I used the following helper function and class:</p> <pre><code>public static MemberAccessor&lt;TReturn&gt; GetMemberAccessor&lt;TObj,TReturn&gt;(Expression&lt;Func&lt;TObj, TReturn&gt;&gt; expr, TObj tar) { var body = expr.Body; MemberExpression memberExpression = null; if (body is UnaryExpression) { var ue = (UnaryExpression)body; memberExpression = (MemberExpression)ue.Operand; } else if (body is MemberExpression) memberExpression = (MemberExpression)body; else throw new NotImplementedException("can't get MemberExpression"); String name = memberExpression.Member.Name; return new MemberAccessor&lt;TReturn&gt;(tar, name); } public class MemberAccessor&lt;T&gt; { private readonly PropertyDescriptor propertyDesc; private readonly Object target; public MemberAccessor(Object target, String propertyName) { this.target = target; this.propertyDesc = TypeDescriptor.GetProperties(target)[propertyName]; } public String Name { get { return propertyDesc.Name; } } public Type Type { get { return propertyDesc.PropertyType; } } public T Value { get { return (T)Convert.ChangeType(propertyDesc.GetValue(target), typeof(T)); } set { propertyDesc.SetValue(target, value); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload