如果我有
public IList<Entity> Children { get; set; }
public NotifyChildren(Func<object, bool> action, object data)
{
foreach (var child in Children)
if (action(data))
/// <-- !!!! need action to work on child this time, not on the original target
//child.NofifyChildren(action, data); <- this doesn't work because of the above requirement
child.NotifyChildren(action.ChangeTargetTo(child), data); // << pseudocode!
}
public void SomeChangeOccured()
{
var changedChild;
NotifyChildren(x => x.SomeHandler(), "somedata");
}我如何改变行动的目标?我可以传递一个委托而不是操作,但是它的.Target也是只读的。目前我觉得做
public NotifyChildren(Expression<Func<Entity, bool>> action, object data)
{
// so that I can do method.Invoke(newtarget, new object[]{data});
NotifyChildren(((MethodCallExpression)action).Method, data);
}也就是说,从动作切换到反射方法调用.但这是一个有点丑陋的,不是吗?
我有一种感觉,解决办法很简单,我以前就知道.只是忘了。
Hm,一种解决方案是让静态委托接受实体作为第一个参数,但我不想这样做。
发布于 2009-10-29 15:06:35
你特别要求的是不可能的。委托表示静态绑定的方法,而您正在寻找动态的方法。要具体地做到这一点,您需要进行反思。
然而,您的代码似乎是以正确的方式构造的,以实现您想要的结果,但是代码看起来并没有被正确地调用。
您将action定义为Func<Entity, bool>,但您传递的是data (即object),而不是child ( Entity)。似乎您应该将其声明为Func<Entity, object, bool>,并这样做:
public IList<Entity> Children { get; set; }
public NotifyChildren(Func<Entity, object, bool> action, object data)
{
foreach (var child in Children)
{
if (action(child, data))
{
child.NofifyChildren(action, data);
}
}
}
public void SomeChangeOccured()
{
NotifyChildren((x, data) => x.SomeHandler(data), "somedata");
}
public bool SomeHandler(object data)
{
return true; // obviously need more robust logic
}发布于 2009-10-29 14:59:40
foreach (var child in Children)
if (action(data))
/// <-- !!!! need action to work on child this time, not on the original target
child.NofifyChildren(action, data); 为什么在这个循环中调用动作?我想你只能在开门见山之前叫一次。
https://stackoverflow.com/questions/1644277
复制相似问题