(需要关于可怕代码的建议)
我试图通过为所有视图模型合并 MVVM 和通用 DataService 类来为我的旧 Windows Phone 应用程序代码带来一些优雅,以调用它们相应的 Web 服务处理程序。
例如,在通知 ViewModel 中,我有:
private ObservableCollection<Notification> _notifications;
public ObservableCollection<Notification> Notifications
{
get
{
return _notifications;
}
}
public void GetNotifications()
{
new DataService().DownloadViewModelData<ObservableCollection<Notification>>(GetNotificationsCallback, "getnotificationslist.ashx");
this.IsDataLoaded = true;
}
public void GetNotificationsCallback(ObservableCollection<Notification> notificationsList)
{
_notifications = notificationsList;
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
NotifyPropertyChanged("Notifications");
});
this.IsDataLoaded = true;
}
在 DataService 类中,我试图创建一个与服务通信的通用方法:
public static string ServerUrl = "http://<ip-address>:<port>/";
public void DownloadViewModelData<T>(Action<T> callbackFunction, string handlerName, bool methodIsPOST = false, List<KeyValuePair<string, string>> querySet = null) where T : class
{
var queryString = "";
if(null != querySet)
{
foreach (KeyValuePair<string, string> tuple in querySet)
{
queryString += tuple.Key + "=" + tuple.Value + "&";
}
queryString = queryString.Remove(queryString.Length - 1, 1);
}
var urlQueryString = ServerUrl + handlerName;
if (!methodIsPOST)
urlQueryString += queryString;
var webRequest = HttpWebRequest.CreateHttp(urlQueryString);
webRequest.ContentType = "application/x-www-form-urlencoded";
Func<AsyncCallback, object, IAsyncResult> requestingMethod = null;
if (methodIsPOST)
{
webRequest.Method = "POST";
webRequest.ContentLength = queryString.Length;
webRequest.BeginGetRequestStream(
a =>
{
System.IO.Stream postStream = webRequest.EndGetRequestStream(a);
byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(queryString);
postStream.Write(byteArray, 0, queryString.Length);
postStream.Close();
webRequest.BeginGetResponse(
b =>
{
using (WebResponse response = webRequest.EndGetResponse(b))
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
callbackFunction(new DataContractJsonSerializer(typeof(T)).ReadObject(response.GetResponseStream()) as T);
}
}
},
null
);
},
null
);
}
else
{
webRequest.Method = "GET";
webRequest.BeginGetResponse(
a =>
{
using (WebResponse response = webRequest.EndGetResponse(a))
{
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
callbackFunction(new DataContractJsonSerializer(typeof(T)).ReadObject(response.GetResponseStream()) as T);
}
}
},
null
);
}
}
问题:
它是使用 lambda 表达式和整体正确的方法来处理 MVVM 的数据层的正确(现代)方式吗(假设我们的项目中有多个模型、视图和视图模型)?
您会推荐这种方法来调用可移植类库 (PCL)中的 Web 服务吗?