2016-08-29 26 views
0

调用静态场法的静态类我有这个规范静态类:使用如何使用反射

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):

public static class OperationSpecs 
{ 

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

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

规范实施反思?我尝试这样做:

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

我遇到错误时要调用调用非静态方法需要一个目标......我需要布尔结果.. 感谢您的帮助!

+0

只是一个题外话的话:我双头呆您的个人资料,看看你从来没有奖励或赞成票正确答案。为了保持每个人的积极性,请将最佳答案投票表决,或者如果答案是正确答案,请勾选灰色勾号。 :) –

回答

2

您正试图使用​​反射调用方法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 }); 
+0

非常感谢,作品! +1 –