谢谢大家再次,结果在第一种方法如下
public class Component
{
public ComponentPart SomeComponentPart1 { get; private set; }
public ComponentPart SomeComponentPart2 { get; private set; }
public Component()
{
SomeComponentPart1 = new ComponentPart(this);
SomeComponentPart2 = new ComponentPart(this);
}
public bool IsMethodCallAcceptable(MethodCallExpression method, object[] parameters)
{
// collect needed information about caller
var caller = (method.Object as ConstantExpression).Value;
var methodName = method.Method.Name;
var paramsArray = new Dictionary<string, object>();
for (int i = 0; i < method.Arguments.Count; i++)
paramsArray.Add((method.Arguments[i] as MemberExpression).Member.Name, parameters[i]);
// make corresponding decisions
if (caller == SomeComponentPart2)
if (methodName == "SomeMethod")
if ((int) paramsArray["intArg"] == 0 || (string) paramsArray["stringArg"] == "")
return false;
return true;
}
}
public class ComponentPart
{
private Component Owner { get; set; }
public ComponentPart(Component owner)
{
Owner = owner;
}
public int SomeMethod(int intArg, string stringArg)
{
// check if the method call with provided parameters is acceptable
Expression<Func<int, string, int>> expr = (i, s) => SomeMethod(intArg, stringArg);
if (!Owner.IsMethodCallAcceptable(expr.Body as MethodCallExpression, new object[] { intArg, stringArg }))
throw new Exception();
// do some work
return stringArg.Length + intArg;
}
public void AnotherMethod(bool boolArg, Dictionary<Guid, DateTime> crazyArg, string stringArg, object objectArg)
{
// check if the method call with provided parameters is acceptable
Expression<Action<bool, Dictionary<Guid, DateTime>, string, object>> expr =
(b, times, arg3, arg4) => AnotherMethod(boolArg, crazyArg, stringArg, objectArg);
if (!Owner.IsMethodCallAcceptable(expr.Body as MethodCallExpression, new [] { boolArg, crazyArg, stringArg, objectArg }))
throw new Exception();
// do some work
var g = new Guid();
var d = DateTime.UtcNow;
}
}
这是变异如何检查方法调用上市,同样的方法也以检查属性中使用的值的变化,而一些ComponentPart的方法和属性可以检查一些公共的Component.State属性(通过ComponentPart.Owner)而不是调用Component.IsMethodCallAcceptable或Component.IsPropertyChangeAcceptable。
来源
2012-07-22 09:44:26
JSP
感谢所有值得尊敬的对话参与者。可能是由于缺乏英语经验,我以不正确的方式使用了一些术语。 – JSP 2012-07-21 18:48:40
该主题不是父类在子类(OOP范式)中的关系,而是组件的单独部分和通用组件代码之间的关系。例如,我们有一个组件CAR,它由四个WHEEL,一个ENGINE等组成。我们可以调用CAR.ENGINE.START,但是如果CAR.FUEL_TANK.GASOLINE_VOLUME = 0,我们的CAR不能移动,所以它的引擎启动不正确。所以我需要检查组件的部件方法调用,并且我的CAR对这些方法足够了解。 – JSP 2012-07-21 18:57:53
现在使用的代表看起来最接受,谢谢你,海德里安。但是我需要写很多代表,同时想写一个通用的检查方法。 – JSP 2012-07-21 18:59:50