samedi 25 juin 2016

Get static field from nested class via expression tree

I have these classes:

public class Entity
{
    public static readonly EntitySchema Schema = new EntitySchema();
}

public abstract class BaseSchema
{
    public abstract string Name {get;}
}

public class EntitySchema : BaseSchema
{
    public override string Name => "Schema";
}

Now, I want to access EntitySchema.Name from a method, which does not know anything about Entity (cannot access the static field).

I could do this with reflection:

static BaseSchema GetSchema<T>()
{
    var pr = typeof(T).GetField("Schema");
    var schema = pr.GetValue(null);
    return schema as BaseSchema;
}

but compared to a direct call Entity.Schema.Name the reflection version is 50x slower.

Is there a way to convert the reflection version into a Expression Tree and precompile the call?





Aucun commentaire:

Enregistrer un commentaire