Note that there are some explanatory texts on larger screens.

plurals
  1. POMatching an interface's ProperyInfo with a class's PropertyInfo
    primarykey
    data
    text
    <p>I use a method similar to the following to get some precomputed metadata related to a Type's properties.</p> <pre><code>MyData GetProperty&lt;T, U&gt;(Expression&lt;Func&lt;T, U&gt;&gt; member) { // Get the property referenced in the lambda expression MemberExpression expression = member.Body as MemberExpression; PropertyInfo property = expression.Member as PropertyInfo; // get the properties in the type T PropertyInfo[] candidates = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); // Find the match foreach (PropertyInfo candidate in candidates) if (candidate == property) return GetMetaData&lt;T&gt;(candidate); throw new Exception("Property not found."); } // Returns precomputed metadata MyData GetMetaData&lt;T&gt;(PropertyInfo property) { ... } </code></pre> <p>As you would expect, it works when used as follows:</p> <pre><code>var data = PropertyInfo((Employee e) =&gt; e.Name); </code></pre> <p>But not when used in the following generic method:</p> <pre><code>void MyGenericMethod&lt;T&gt;(int id) where T : IEmployee { var data = PropertyInfo((T e) =&gt; e.Name); } </code></pre> <p>It fails because the declaring type of <code>property</code> in the first method is now <code>IEmployee</code>, so the property in the lambda doesn't match the property in the type. <strong>How can I get them to match</strong>, without relying on the names of the properties? (There can be multiple properties with the same name if interfaces are implemented explicitly, so <code>p1.Name == p2.Name</code> won't cut it).</p>
    singulars
    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. 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