今年早些时候我为此写了一个解决方案:Components and ComponentEntities
组件之间的关系是通过带注释的属性和方法定义的,如下所示:
// Link to component of type B through a property.
// The name doesn't matter.
[ComponentLink]
B B { get; set; }
// Called when components are added or removed.
// The parameter type acts as a filter.
[NotifyComponentLinked]
void Added(object o)
{ Console.WriteLine(this.GetType().Name + " linked to " + o.GetType().Name + "."); }
[NotifyComponentUnlinked]
void Removed(object o)
{ Console.WriteLine(this.GetType().Name + " unlinked from " + o.GetType().Name + "."); }
// Attaches to events in compenents of type D and E.
// Rewriting this with Lambda Expressions may be possible,
// but probably would be less concise due to lack of generic attributes.
//
// It should be possible to validate them automatically somehow, though.
[EventLink(typeof(D), "NumberEvent")]
[EventLink(typeof(E), "NumberEvent")]
void NumberEventHandler(int number)
{ Console.WriteLine("Number received by F: " + number); }
ComponentEntities 项目包含将自身作为组件添加到自身或添加到它们的实体的集合,以避免全局单例。如果您想要一个带有 Components 和 ComponentsTest(使用示例)项目的 VS 解决方案,请克隆bundle 存储库。
组件的许可证是 LGPL,到目前为止我还没有获得 ComponentEntities 的许可证(我刚刚将存储库设置为公开),但是如果你需要的话,你可能可以在大约 10 分钟内写出我上面写的东西。