[英]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 ? 如何使用反射调用TestSpec.IsSatisfiedBy(someType)? 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! 调用“调用非静态方法”需要目标时出现错误。我需要获取布尔结果。
You are trying to invoke the method IsSatisfiedBy
using reflection. 您正在尝试使用反射调用方法IsSatisfiedBy
。 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 });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.