lundi 29 août 2016

How to call static field method in static class using reflection

I gave this static class with Specifications:

public static class OperationSpecs
{

    public static ISpecification<TestEntity> TestSpec = new Specification<TestEntity>(
        o =>
        {

            return (o.Param1== 1 &&
                    o.Param2== 3 
                );
        }
    );

Specification implementation:

public class Specification<T> : ISpecification<T>
{
    private Func<T, bool> expression;
    public Specification(Func<T, bool> expression)
    {
        if (expression == null)
            throw new ArgumentNullException();
        else
            this.expression = expression;
    }

    public bool IsSatisfiedBy(T o)
    {
        return this.expression(o);
    }
}

How can I call TestSpec.IsSatisfiedBy(someType) using reflection ? I tried this:

            var specAttr = op.GetCustomAttribute<OperationSpecificationAttribute>();
            var specType = specAttr.SpecificationType;
            var specTypeMethodName = specAttr.SpecificationMethodName;
            var specField = specType.GetField(specTypeMethodName, BindingFlags.Public | BindingFlags.Static);

            if (specField != null)
            {
                var specFieldType = specField.FieldType;
                var result2 = specField.GetValue(null).GetType().GetMethod("IsSatisfiedBy").Invoke(null, new object[] { entity });
            }

I got ERROR when call Invoke Non-static method requires a target ... I need to get boolean result.. Thanks for Help!





Aucun commentaire:

Enregistrer un commentaire