[英]Cannot implicitly convert type 'System.Threading.Tasks.Task<String> to 'string'
I have a WCF Service with the method to return a string. 我有一个WCF服务,带有返回字符串的方法。
WCF Service : WCF服务:
public string selectName(int input)
{
string firstN, surN,result;
con.Open();
SqlCommand cmd = new SqlCommand("SELECT FirstName, Surname FROM tbUserAccounts WHERE StudentID = @ID", con);
cmd.Parameters.Add("@ID", System.Data.SqlDbType.Int).Value = input;
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())
{
firstN= reader["FirstName"].ToString();
surN = reader["Surname"].ToString();
result = firstN + " " + surN;
con.Close();
return result;
}
else
{
con.Close();
return string.Empty;
}
}
This method works on the web service end. 此方法在Web服务端起作用。 I've tried with WCFTest client and returns the values expected. 我已经尝试过使用WCFTest客户端并返回期望的值。 Now on the application side I'm trying to use these values to add to my static class variables : 现在在应用程序端,我尝试使用这些值添加到我的静态类变量中:
private void btnSignIn_Click_1(object sender, RoutedEventArgs e)
{
Login._name = ServiceClientObj.selectNameAsync(int.Parse(studentIdBox.Text));
Frame.Navigate(typeof(WelcomePage));
}
the ' ServiceClientObj.selectNameAsync(int.Parse(studentIdBox.Text)); ' ServiceClientObj.selectNameAsync(int.Parse(studentIdBox.Text)); ' is underlined with an error saying '下划线有错误提示
Cannot implicitly convert type 'System.Threading.Tasks.Task<String> to 'string'
I'm not familiar with WCF service so I don't understand fully about the use of async. 我对WCF服务不熟悉,所以我对异步的使用不甚了解。
Any help or explanation would be appreciated. 任何帮助或解释将不胜感激。 Thank you. 谢谢。
Try it like this: 像这样尝试:
private async void btnSignIn_Click_1(object sender, RoutedEventArgs e)
{
Login._name = await ServiceClientObj.selectNameAsync(int.Parse(studentIdBox.Text));
Frame.Navigate(typeof(WelcomePage));
}
Async method selectNameAsync
returns Task<string>
which is kind of a promise that it will return string
in future, to wait this string result you can use keyword await
, but to use it your method should have async
keyword. 异步方法selectNameAsync
返回Task<string>
,这是对将来会返回string
的一种保证,可以使用关键字await
来等待此字符串结果,但是要使用它,您的方法应具有async
关键字。
Or you can use synchronous version of this method selectName
if it's also generated by WCF, code will be like this: 或者也可以使用此方法selectName
同步版本(如果它也是由WCF生成的),代码将如下所示:
private void btnSignIn_Click_1(object sender, RoutedEventArgs e)
{
Login._name = ServiceClientObj.selectName(int.Parse(studentIdBox.Text));
Frame.Navigate(typeof(WelcomePage));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.