2

Suppose i have the following class in C#:

public class B : A
{
    public Int32 B_ID;
    public String B_Value;

    public Int32 getID()
    {
        return B_ID;
    }

    public void setID(Int32 value)
    {
        B_ID = value;
    }
}

Based on Reflection, can I get the name of the field used by getID() (and/or) setID() method? (in case, [B_ID]) I'm coding a persistence framework and it would be useful to identify the key name of a table, which is enclosed by both methods above.

It seems that ReturnParameter property of RuntimeMethodInfo has a property called Name that should help me with this, but it's comming null.

To get that RuntimeMethodInfo object, i'm getting Members of an instance of B class using this BindingFlags enums:

  • BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly

How can I get this field name? This behavior should be the same with properties.

Thanks in advance

rsfurlan90
  • 31
  • 1
  • 7

1 Answers1

2

I am afraid that's impossible because the field name is the part of the implemented code and reflection has no clue how to retrieve it. Persistent frameworks usually use a kind of mapping to provide such information.For example you can use a xml file or you can use attirbutes over your fields to introduce them as key or columns of your table something like this :

[Table(name="MyTable")]    
public class B : A
    {

[Key(column_name="id")]    
public Int32 B_ID;
        public String B_Value;

        public Int32 getID()
        {
            return B_ID;
        }

        public void setID(Int32 value)
        {
            B_ID = value;
        }
    }
Beatles1692
  • 5,214
  • 34
  • 65
  • First, thanks you for the answer, it was so useful to me. Sorry for my delayed response, i've working too much in that question until you show me the easiest way by using Custom Attributes. Based on this, those getID and setID methods are not necessary anymore. +1 – rsfurlan90 Jul 26 '12 at 17:17