Martin Haščák Martin Haščák - 3 months ago 15
ASP.NET (C#) Question

How to call static field method in static class using reflection

I have 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!

Answer

You are trying to invoke the method IsSatisfiedBy using reflection. In contradiction to your title, this method is NOT a static method, it is an instance method. You you need to invoke the method WITH it's instance:

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

or in short:

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