Peter Duniho
9/22/2008 8:01:00 PM
On Mon, 22 Sep 2008 12:51:32 -0700, Shmuel <matti@meikalainen.com> wrote:
> Hi,
>
> I need to get public fields that are set as follows:
>
> private string _name;
In your example, "_name" is not a public field and "name" is a property,
not a field. So, your question is already self-contradicting.
> public string name
> {
> set { _name = value; }
> get { return _name; }
> }
>
> I've tried something like this:
>
> Language l = Language.createEmptyInstance();
> l.name = "ADSFAFDADSF";
>
> FieldInfo field = l.GetType().GetField("_name", BindingFlags.GetField |
> BindingFlags.NonPublic | BindingFlags.Instance |
> BindingFlags.Public);
> Object val = field.GetValue(l);
>
> MessageBox.Show(l.ToString() + "\n\n" + val.ToString());
>
> It works for normal variables, but not those that are set by setters and
> getters.
What isn't working for you? The fact that a field, private or otherwise,
is accessed in a property doesn't change anything about how the _field_
itself might be accessed via reflection. In your example, you do appear
to be allowing for the possibility of a non-public field, so the code you
posted doesn't seem to have any obvious problem with it. It should work
fine.
Of course, without a concise-but-complete code sample, it's not possible
to know for sure. For example, to assert that the code you posted works
fine, I need to make the assumption that the field and property described
are in the class "Language". But that seems like a reasonable assumption
here.
Pete