[英]How do I include specs for a base class in the specs for an inherited class?
[英]How do I InvokeMember in inherited class that is only implemented in base
场景是我正在更改“请求”的状态,有时新状态是暂时的,需要立即更改为另一状态。 因此,我处于基类WorkflowCommandBase中的一个方法中:
public virtual Request Execute()
{
ChangeRequestStatus();
QueueEmails();
TrackRequestStatus();
return ExecuteAutoTransitionStatus(GetTransitionStatus());
}
最后一行尝试针对新状态再次执行该方法(来自继承的类namedType),但是我调用的方法在namedType中不存在,它在基础中实现。 有可能这样做吗? 还是在这种情况下需要在继承的类中重写Execute方法?
private Request ExecuteAutoTransitionStatus(string commandName)
{
if (String.IsNullOrEmpty(commandName))
{
return Request;
}
Type calledType = Type.GetType(commandName);
return (Request)calledType.InvokeMember(
"Execute",
BindingFlags.InvokeMethod
| BindingFlags.Public | BindingFlags.Instance,
null,
null,
new Object[]
{Request, TarsUser, GrantRepository, TrackingRepository});
}
如果有帮助,这是类图的一部分。
好吧,根据您的评论,您在问题中所写的内容和尝试做的内容可能会出现间断。 因此,我将尝试涵盖所有基础。
如果Execute方法是静态的并且在基类上定义,则需要将BindingFlags.FlattenHierarchy添加到绑定标志中:
BindingFlags.InvokeMethod | BindingFlags.Public
| BindingFlags.Static | BindingFlags.FlatternHierarchy
这似乎是最可能出现的问题,因为您说它找不到方法,但是此标志仅在搜索静态成员时才有效。
另一方面,如果该方法不是静态的,则您具有的绑定标志是正确的,但是您需要使用该类型的实例来对其进行操作。 根据构造具体类型的复杂程度,您可能只需要使用Activator类就可以摆脱困境 ,否则您可能需要创建某种工厂。
@马丁:谢谢你的帮助。
我发布此信息以防其他人使用。
private Request ExecuteAutoTransition(Type newStatus)
{
// No transition needed
if (newStatus == null)
{
return Request;
}
// Create an instance of the type
object o = Activator.CreateInstance(
newStatus, // type
new Object[] // constructor parameters
{
Request,
TarsUser,
GrantRepository,
TrackingRepository
});
// Execute status change
return (Request) newStatus.InvokeMember(
"Execute", // method
BindingFlags.Public
| BindingFlags.Instance
| BindingFlags.InvokeMethod, // binding flags
Type.DefaultBinder, // binder
o, // type
null); // method parameters
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.