C# 如何使用反射调用静态类中的静态字段方法
我有一个带规格的静态类:C# 如何使用反射调用静态类中的静态字段方法,c#,asp.net,reflection,C#,Asp.net,Reflection,我有一个带规格的静态类: public static class OperationSpecs { public static ISpecification<TestEntity> TestSpec = new Specification<TestEntity>( o => { return (o.Param1== 1 && o.Param2=
public static class OperationSpecs
{
public static ISpecification<TestEntity> TestSpec = new Specification<TestEntity>(
o =>
{
return (o.Param1== 1 &&
o.Param2== 3
);
}
);
公共静态类操作规范
{
公共静态IsSpecification TestSpec=新规范(
o=>
{
返回值(o.Param1==1&&
o、 参数2==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);
}
}
公共类规范:i规范
{
私有Func表达式;
公共规范(Func表达式)
{
if(表达式==null)
抛出新ArgumentNullException();
其他的
这个表达式=表达式;
}
公共学校被(TO)认可
{
返回这个表达式(o);
}
}
如何使用反射调用TestSpec.Issatifiedby(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 });
}
var specAttr=op.GetCustomAttribute();
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(“Issatifiedby”).Invoke(null,新对象[]{entity});
}
调用非静态方法需要目标时出错…我需要得到布尔结果。。
感谢您的帮助!您正在尝试使用反射来调用方法
已被
满足。与您的标题相反,此方法不是静态方法,而是实例方法。您需要使用其实例调用该方法:
var instance = specField.GetValue(null);
var instanceType = instance.GetType();
var methodInfo = instanceType.GetMethod("IsSatisfiedBy");
var result2 = methodInfo.Invoke(instance, new object[] { entity }); // <<-- instance added.
您正试图使用反射调用方法
Issatifiedby
。与您的标题相反,此方法不是静态方法,而是实例方法。您需要使用其实例调用该方法:
var instance = specField.GetValue(null);
var instanceType = instance.GetType();
var methodInfo = instanceType.GetMethod("IsSatisfiedBy");
var result2 = methodInfo.Invoke(instance, new object[] { entity }); // <<-- instance added.
只是一句题外话:我打开你的个人资料,看到你从不奖励或提高正确答案的投票率。为了保持每个人的积极性,请给好的答案投票,或者如果答案是正确的,请勾选灰色勾号。:)只是一句题外话:我打开你的个人资料,看到你从不奖励或提高正确答案的投票率。为了永远保持正确答案如果答案正确,请投票选出正确答案或勾选灰色勾号