Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Hmm. I thought <code>GetFields</code> gets you members from all the way up the chain, and you had to explicitly specifiy <code>BindingFlags.DeclaredOnly</code> if you <em>didn't</em> want inherited members. So I did a quick test, and I was right.</p> <p>Then I noticed something:</p> <blockquote> <p>I would like to update all <strong>properties</strong> from MyObject to another using Reflection. The problem I am coming into is that the particular object is inherited from a base class and those base class <strong>property</strong> values are not updated.</p> <p>The below code copies over top level property values.</p> <pre><code>public void Update(MyObject o) { MyObject copyObject = ... FieldInfo[] myObjectFields = o.GetType().GetFields( BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); </code></pre> </blockquote> <p>This will get only <strong>fields</strong> (including private fields <em>on this type</em>), but not <strong>properties</strong>. So if you have this hierarchy (please excuse the names!):</p> <pre><code>class L0 { public int f0; private int _p0; public int p0 { get { return _p0; } set { _p0 = value; } } } class L1 : L0 { public int f1; private int _p1; public int p1 { get { return _p1; } set { _p1 = value; } } } class L2 : L1 { public int f2; private int _p2; public int p2 { get { return _p2; } set { _p2 = value; } } } </code></pre> <p>then a <code>.GetFields</code> on <code>L2</code> with the <code>BindingFlags</code> you specify will get <code>f0</code>, <code>f1</code>, <code>f2</code>, and <code>_p2</code>, but NOT <code>p0</code> or <code>p1</code> (which are properties, not fields) OR <code>_p0</code> or <code>_p1</code> (which are private to the base classes and hence an objects of type <code>L2</code> <em>does not have</em> those fields.</p> <p>If you want to copy properties, try doing what you're doing, but using <code>.GetProperties</code> instead.</p>
 

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