上下文:.NET 3.5,VS2008.我不确定这个问题的标题,所以也可以自由评论标题:-)
这是场景:我有几个类,比如Foo和Bar,它们都实现了以下接口:
public interface IStartable
{
void Start();
void Stop();
}
Run Code Online (Sandbox Code Playgroud)
现在我想要一个容器类,它在构造函数中获取一个IEnumerable <IStartable>作为参数.反过来,这个类也应该实现IStartable接口:
public class StartableGroup : IStartable // this is the container class
{
private readonly IEnumerable<IStartable> startables;
public StartableGroup(IEnumerable<IStartable> startables)
{
this.startables = startables;
}
public void Start()
{
foreach (var startable in startables)
{
startable.Start();
}
}
public void Stop()
{
foreach (var startable in startables)
{
startable.Stop();
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以我的问题是:如果不手动编写代码,并且没有代码生成,我怎么能这样做呢?换句话说,我想要像以下一样.
var arr = new IStartable[] { new Foo(), new Bar("wow") };
var mygroup = …Run Code Online (Sandbox Code Playgroud)