我认为你只需要一个字典<Widget>和一个合适的Widget类,其中包含对其他Widgets的引用。这可能有助于将其定制为自定义词典,以便您可以简单地添加一个Widget并让它从Widget的FilePath属性派生出键。
public class WidgetDictionary : Dictionary<string,Widget>
{
... provide suitable constructors ...
public void Add(Widget widget)
{
if (widget != null && !this.ContainsKey(widget.FilePath))
{
this.Add(widget.FilePath, widget);
}
}
}
public class Widget
{
public string FilePath { get; set; }
private List<Widget> widgets = new List<Widget>();
public IEnumerable<Widget> Widgets
{
get { return widgets; }
}
...code to add/remove widgets from list...
}
然后要做(1)你只需通过文件路径查看小部件存储库中的小部件。
var repository = new WidgetDictionary();
string filePath = ...
var widget = repository[filePath];
要做(2)可以在更改文件路径后删除小部件并重新添加到存储库。对其他小部件所持有的小部件的引用仍然有效。
var widget = repository[filePath];
repository.Remove(filePath);
widget.FilePath = newFilePath;
repository.Add(widget);
EDIT: this could probably be implemented as a method on the
dictionary as well.
public void UpdatePath(Widget widget, string newPath)
{
if (string.IsNullOrEmpty(newPath))
throw new ArgumentNullException("newPath");
var widget = this.ContainsKey(widget.FilePath)
? this[widget.FilePath]
: null;
if (widget != null)
{
this.Remove(widget.FilePath);
}
widget.FilePath = newPath;
this.Add(widget);
}
要做(3)只需引用属性。
var filePath = widget.FilePath;
如果你想自动拥有,当它被删除的其他部件删除其引用到窗口小部件(配置),你可能会想有Widget类实现IDisposable,不得不添加事件处理程序的能力一个dispose事件,以便感兴趣的小部件可以注册一个方法,该方法将从它们的相关小部件集合中移除正在部署的小部件。有关如何设置和使用事件处理程序,请参见this MSDN section。
这个答案和其他人回答了这个问题的部分内容,但这是解决主要问题的答案,也是最简洁的答案。谢谢! – 2009-04-11 20:26:38