我認爲你只需要一個字典<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