2017-05-25 76 views
0

我有一些代碼,我覺得我應該能夠縮短難以置信的,但我不知道如何去做。我可以使用反射縮短此代碼嗎?

我有一個名爲消息的基類,並可能從它派生的類。

namespace ModalVR { 
    public class Message { 
     public string message; 

     public Message() { 
      this.message = this.ToString(); 
     } 
    } 
} 

子類轉換爲JSON,我有一個函數接收這個JSON,我需要創建合適的類。然而,它的功能有一個巨大的案例陳述,我覺得必須有一個更好的方式來做到這一點。這就是這個函數的樣子。

public Message ConstructMessageFromJSON(string JSON) { 
    string messageName = JsonUtility.FromJson<Message>(JSON).message; 

    Message derivedMessage = null; 

    switch(messageName) { 
     case "ModalVR.GetBatteryInfo": { 
      derivedMessage = JsonUtility.FromJson<GetBatteryInfo>(JSON); 
      break; 
     } 

     case "ModalVR.GetBatteryInfoResponse": { 
      derivedMessage = JsonUtility.FromJson<GetBatteryInfoResponse>(JSON); 
      break; 
     } 

     // Many more case statements snipped out 

     default: { 
      LogManager.Log("Received unknown message of " + messageName, LogManager.LogLevel.Error); 
      break; 
     } 
    } 

    return derivedMessage; 
} 

有沒有什麼辦法可以用簡單的東西來代替這個龐大的案例陳述?

在此先感謝 約翰·勞瑞

+0

這可能會有幫助。 https://stackoverflow.com/questions/36239705/serialize-and-deserialize-json-and-json-array-in-unity – hatchet

+0

這真的好像虛擬功能的情況。您正在切換類型,以便僅在剛剛打開的類型中執行一些不同的操作。 –

回答

1

僅使用反射,您可以:

string messageName = "ModalVR.GetBatteryInfo"; 
Type messageType = Assembly.GetAssembly(typeof(Message)).GetType(messageName); 
Message derivedMessage = (Message)JsonUtility.FromJson(json, messageType); 

它檢索已定義Message類的Assembly,然後在此程序集中搜索請求的類型。

+0

這正是我所需要的。這是最好的解決方案,因爲它處理添加更多消息而不需要任何附加代碼。謝謝 – Dalanchoo

0

最簡單的方法是創建一個這樣的解釋:

var typeMatches = new Dictionary<string, Type> 
    { 
     {"ModalVR.GetBatteryInfo", typeof(GetBatteryInfo)} 
    }; 

,然後就從它那裏得到的值:(這是C#7)

if (!typeMatches.TryGetValue(messageName, out var messageType)) 
    { 
     LogManager.Log("Received unknown message of " + messageName, LogManager.LogLevel.Error); 
     return; 
    } 

    var derivedMessage = (Message) JsonUtility.FromJson(JSON, messageType);