Search code examples
c#reflectionmethodinfobindingflags

Get ReturnParameter's Name property of a RuntimeMethodInfo object using Reflection (C#)


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


Solution

  • 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;
            }
        }