[英]What is the best way to serialize, return and consume complex C# object from an MVC3 app?
[英]What is an ideal way to return a status code or a complex object in C#?
我想弄清楚如何最好地處理以下場景。 我有一台服務器接收消息,處理它們,然后將響應發送回客戶端。 我想讓processing
步驟返回有關執行處理結果和某些情況下的對象的詳細信息。
我有以下代碼:
public void HandleMessage(Connection conn, Packet packet) {
var somedata = packet.Read();
var result = Process(somedata);
if (result == typeof(Message))
SendA(result);
if (result == typeof(MyObject))
SendB(result, extraInfo);
}
public [what goes here] Process(object data) {
if (validated)
return data;
else
return Message.Failed;
}
我想要做的是創造責任分離。
我應該嘗試實現什么樣的設計來實現這樣的目標?
避免使用typeof()
並更傾向於使用is
語法:
if (result is Message)
我的建議是將對象包裝在一個狀態中,或者一起跳過狀態結果,然后從packet.Read()
方法返回一個接口,並直接調用接口方法:
public StateResult
{
public StateResultEnum Result;
public IDataObject Data;
}
IDataObject將是一個接口,它將公開可能根據其中包含的數據而變化的方法。
例如:
public interface IDataObject
{
string GetData();
}
public Message : IDataObject
{
public string Contents;
public Message(string contents)
{
Contents = contents;
}
public string GetData()
{
//Convert the string to json
return json;
}
}
public MyObject : IDataObject
{
public string Contents;
public string ExtraInfo;
public MyObject(string contents, string extraInfo)
{
Contents = contents;
ExtraInfo = extraInfo;
}
public string GetData()
{
//Convert the string to json (And include extraInfo)
return json;
}
}
底線:避免在任何地方使用object
。 如果可以驗證您的數據,請創建一個IValidatable
接口,該接口公開一個名為Validate()
的方法。 當您從函數返回IValidatable
,無論它是哪個對象( MyObject
類型或Message
類型)都無關緊要,它們都提供了驗證方法,這些方法在您的界面中定義。 因此,如果您在沒有某些轉換的情況下無法執行obj.ExtraInfo
,您將能夠調用obj.Validate()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.