如何使用反射在静态类中调用静态字段方法

时间:2016-08-29 13:00:45

标签: c# asp.net reflection

我有这个带规格的静态类:

public static class OperationSpecs
{

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

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

规范实施:

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

如何使用反射调用TestSpec.IsSatisfiedBy(someType)?我试过这个:

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

调用Invoke时,我得到了ERROR非静态方法需要一个目标...我需要得到布尔结果.. 谢谢你的帮助!

1 个答案:

答案 0 :(得分:3)

您正尝试使用反射调用方法IsSatisfiedBy。与您的标题相矛盾,此方法不是静态方法,而是实例方法。您需要使用它的实例调用方法:

var instance = specField.GetValue(null);
var instanceType = instance.GetType();
var methodInfo = instanceType.GetMethod("IsSatisfiedBy");
var result2 = methodInfo.Invoke(instance, new object[] { entity }); // <<-- instance added.

或简称:

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