簡體   English   中英

如何使用反射在靜態類中調用靜態字段方法

[英]How to call static field method in static class using 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 });
            }

調用“調用非靜態方法”需要目標時出現錯誤。我需要獲取布爾結果。

您正在嘗試使用反射調用方法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 }); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM