假設方案:對象屬性如何知道它的父項?
class ComplexProperty
{
string PropertyName {get; set;}
string Description {get; set;}
string GetParentName(); // How can this be implemented?
}
class Parent
{
string ParentName {get; set;}
ComplexProperty Property {get; set;}
}
的問題是從ComplexProperty
內得到ParentName。
我提出的最佳解決方案是使用Parent的構造函數來初始化屬性,但是當您從不同位置設置屬性時,這很容易出現錯誤並失敗。
例如:
class Parent
{
public Parent()
{
ComplexProperty = new ComplexProperty(this); // Store an instance of the parent inside the property
}
string ParentName {get; set;}
ComplexProperty Property {get; set;}
}
這個任何想法?這種架構有沒有最佳做法?請注意,ComplexProperty
將永遠是特定接口實現的孩子,所以反射是一種可行但不是理想的解決方案。
它是否必須有公共二傳手? – Paddy
你能否解釋一下你的意思是「容易出錯,當你從不同的地方設置房產時失敗」? YOu可以考慮修改ComplexProperty來獲得另一個名爲ParentName的屬性,或者可能有一個名爲SetParentName的方法,它可以設置一個本地私有變量。現在在'ComplexProperty Property {get;組; }'你可以修改setter來改變它。 – ryadavilli
'ComplexProperty'必須根據它的上下文(基本上是保存它的項目)收集一些信息並進行計算。例如,它需要獲取字符串屬性的名稱,而不是類的名稱,因此它需要訪問排序實例。 –