Guerrilla
Guerrilla

Reputation: 14866

Get value of a protected field

My method is being passed an object as parameter from third party code. The class in question is called: SqlExpression<T>.

This class has the following protected field:

protected List<ModelDefinition> tableDefs = new List<ModelDefinition>();

I need the info inside that property but I have checked the class and there is no public accessor.

I tried making a child class:

public class SqlExpressionExtension<T> : SqlExpression<T>
{
    public SqlExpressionExtension(IOrmLiteDialectProvider dialectProvider) : base(dialectProvider)
    {
    }

    public List<Type> GeTableTypes()
    {
        return this.tableDefs.Select(x => x.ModelType).ToList();
    }
}

And then casting SqlExpression<T> to SqlExpressionExtension<T> like so:

var types = ((SqlExpressionExtension<T>)query).GeTableTypes();

But I get an exception that it is unable to cast the type.

What is the right way to get this data?

Upvotes: 2

Views: 276

Answers (1)

bwakabats
bwakabats

Reputation: 703

You could use reflection to get to the field:

Get the type:

var queryType = query.GetType();

Then get the FieldInfo:

var tableDefsField = queryType.GetField("tableDefs", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);

Finally get the value of the field:

var tableDefs = (List<ModelDefinition>)tableDefsField.GetValue(query);

However, like any use of reflection in this way, because it is not public, you cannot guarantee this will work in future versions of SqlExpression<T>

Upvotes: 5

Related Questions