2009-06-17 40 views
0

我目前遇到的問題是將多個GUI字段映射到對象屬性(即表示層到業務邏輯層映射)。更具體地說,這是在VB.Net 2.0 WinForms中。業務對象映射的GUI VB.Net

解決方案的性質要求我們有4列,它們在我們的GUI上表現出相同類型的行爲 - 每列包含11個文本框(我們只使用這個小樣本大小,因爲問題超出了11個文本框)。

什麼我目前在做的所有四列的設置每個文本框的標籤值,像這樣:

Textbox1.tag = "name" 
Textbox2.tag = "type" 
Textbox3.tag = "speed" 

當一個事件是由文本框(如按鍵)提出的,我看父容器,其標籤也設置爲映射特定對象的字符串。我將它與文本框的標記一起使用來確定我需要設置的對象的屬性。總的來說,它看起來像這樣:

dim objectToMapTo //the generic parent object which all my custom myObjects inherit from 

select case sender.parent.tag //the parent object that the property needs to map to 
    case "column1" 
     objectToMapTo = myObject1 
    case "column2" 
     objectToMapTo = myObject2 
    case "column3" 
     objectToMapTo = myObject3 
    case "column4" 
     objectToMapTo = myObject4 
end select 

select case sender.tag //the actual textbox's tag value which maps to the property 
    case "name" 
     objectToMapTo.Name = sender.text //sender.text is conceptual for 
     //the data that needs to be set -- i.e. this could be a calculated 
     //number based on the text, or simply a string, etc 
    case "type" 
     objectToMapTo.Type = sender.text 
    case "speed" 
     objectToMapTo.Speed = sender.text 
    ... 
end select 

正如你所看到的,這可能會變得非常糟糕,相當快。目前我們設置了一些可以映射到的奇怪屬性 - 因此select語句非常長 - 其中很多嵌入了多個方法來嘗試和嘗試DRY(我已經淡化了代碼本質上是一個概念實現)。

問題是:我該如何重構這個?我試圖在一定程度上使用字典/散列,但它要麼變得過於複雜,要麼只是簡單地沒有實現實現,因爲它更加複雜化了問題。

感謝您的幫助。

回答

1

您通過將標籤設置爲對象而解決的第一個問題。由於標記不是字符串,而是類型對象。

而您使用反射解決的第二個問題,但比標記中的值必須完全匹配屬性名稱。

_objectToMapTo.GetType().InvokeMember(sender.tag,BindingFlags.Instance Or BindingFlags.Public,Nothing, _objectToMapTo, New Object() {sender.text}) 

聲明反射很接近但可能不是100%正確。

+0

實際上反射效果很好。唯一的問題是每個值都設置得更復雜一點。所以我們可能會把它像objectToMap.Customer.Name = sender.text,然後objectToMap.Asset.Type = sender.text - 因此它基本上需要獲取/設置嵌套的屬性,這給它一個複雜的添加層 – MunkiPhD 2009-06-17 16:14:24