【发布时间】:2011-12-26 12:33:25
【问题描述】:
我有以下:
public interface IBehaviour
{
event EventHandler Completed;
void Execute();
}
public interface IBehaviourA : IBehaviour
{
// Some specific stuff here
object A { get; set; }
}
public interface IBehaviourB : IBehaviour
{
// Some specific stuff here
object B {get;set;}
}
public interface IBehaviourQueue
{
void Run();
BehaviourQueueItem<IBehaviour> AddBehaviour<T>() where T : IBehaviour;
}
public class BehaviourQueue : Queue<BehaviourQueueItem<IBehaviour>>, IBehaviourQueue
{
private IBehaviourFactory factory;
public BehaviourQueue(IBehaviourFactory factory)
{
this.factory = factory;
}
public BehaviourQueueItem<IBehaviour> AddBehaviour<T>() where T:IBehaviour
{
T behaviour = factory.GetNew<T>();
var queueItem = new BehaviourQueueItem<IBehaviour>(behaviour);
Enqueue(queueItem);
return queueItem;
}
public void Run()
{
//Run each queue item
}
}
public class BehaviourQueueItem<T>
{
public IBehaviour behaviour;
public BehaviourQueueItem(IBehaviour behaviour)
{
this.behaviour = behaviour;
}
public void WhenComplete(Func<T, bool> action)
{
CompletedAction = action;
}
public BehaviourQueueItem<T> ConfigureFor<Z>(Action<Z> dow) where Z : IBehaviour
{
dow((Z)behaviour);
return this;
}
}
这是我能写的:
var q =new BehaviourQueue(new BehaviourFactory());
q
.AddBehaviour<IBehaviourA>()
.ConfigureFor<IBehaviourA>(x => x.A = "someValueA")
.WhenComplete(x => DoStuffWithSomeProperty(((IBehaviourA)x).A));
q
.AddBehaviour<IBehaviourB >()
.ConfigureFor<IBehaviourB >(x => x.B = "someValueB")
.WhenComplete(x => DoStuffWithSomeProperty(((IBehaviourB)x).B));
我不太喜欢的是我每次都必须指定我指的是哪种类型的 IBehaviour。 我希望能够写:
var q =new BehaviourQueue(new BehaviourFactory()); // Queue here is of IBehaviour
q
.AddBehaviour<IBehaviourA>()
.Configure(x => x.A = "someValueA")
.WhenComplete(x => DoStuffWithSomeProperty(x.A));
q
.AddBehaviour<IBehaviourB>()
.Configure(x => x.B = "someValueB")
.WhenComplete(x => DoStuffWithSomeProperty(x.B));
你知道我应该写什么来创建一个基本类型的列表并添加特定的项目并流畅地配置它吗?
Edit1:删除了一些代码以避免混淆。我的最终目标是编写上面的代码。
非常感谢
【问题讨论】:
-
如果您没有得到满意的答案,您可以考虑在the StackExchange Code Review site 上发帖。
标签: c# queue covariance fluent-interface