Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><a href="https://stackoverflow.com/questions/4292740/get-property-from-a-generic-object-in-c/4292764#4292764">Oded is right</a>, it doesn't seem (to him or me) to make any sense to try and make this method generic. You are trying to genericize a method whose functionality is actually specific to a few types.</p> <p>Now, that said, it seems the <em>bulk</em> of the function is independent of this property you want to access. So why not split it into two parts: that which can be genericized, and that which can't:</p> <p>Something like this:</p> <pre><code>void BindElements&lt;T, TProperty&gt;(IEnumerable&lt;T&gt; dataObjects, Func&lt;T, TProperty&gt; selector) { Paragraph para = new Paragraph(); foreach (T item in dataObjects) { // Notice: by delegating the only type-specific aspect of this method // (the property) to (fittingly enough) a delegate, we are able to // package MOST of the code in a reusable form. var property = selector(item); InlineUIContainer uiContainer = this.CreateElementContainer(property) para.Inlines.Add(uiContainer); } FlowDocument flowDoc = new FlowDocument(para); this.Document = flowDoc; } </code></pre> <p>Then your overloads dealing with specific types, e.g., <code>IPerson</code>, can reuse this code (which I suspect may be what you were after all along—code reuse):</p> <pre><code>public void BindPeople(IEnumerable&lt;IPerson&gt; people) { BindElements(people, p =&gt; p.FirstName); } </code></pre> <p>...then for <code>IOrder</code>:</p> <pre><code>public void BindOrders(IEnumerable&lt;IOrder&gt; orders) { BindElements(orders, o =&gt; p.OrderNumber); } </code></pre> <p>...and so on.</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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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