【问题标题】:Cannot implicitly convert type 'System.Threading.Tasks.Task<String> to 'string'无法将类型 'System.Threading.Tasks.Task<String> 隐式转换为 'string'
【发布时间】:2015-12-26 22:38:44
【问题描述】:

我有一个带有返回字符串方法的 WCF 服务。

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;
        }

   }

此方法适用于 Web 服务端。我已经尝试过使用 WCFTest 客户端并返回预期的值。 现在在应用程序方面,我正在尝试使用这些值添加到我的静态类变量中:

 private void btnSignIn_Click_1(object sender, RoutedEventArgs e)
    {

        Login._name = ServiceClientObj.selectNameAsync(int.Parse(studentIdBox.Text));
        Frame.Navigate(typeof(WelcomePage));


    }

'ServiceClientObj.selectNameAsync(int.Parse(studentIdBox.Text));' 带有下划线并带有错误提示

Cannot implicitly convert type 'System.Threading.Tasks.Task<String> to 'string'

我不熟悉 WCF 服务,所以对异步的使用不是很了解。

任何帮助或解释将不胜感激。谢谢。

【问题讨论】:

    标签: c# sql win-universal-app wcfserviceclient


    【解决方案1】:

    试试这样:

    private async void btnSignIn_Click_1(object sender, RoutedEventArgs e)
    {
        Login._name = await ServiceClientObj.selectNameAsync(int.Parse(studentIdBox.Text));
        Frame.Navigate(typeof(WelcomePage));
    }
    

    异步方法selectNameAsync返回Task&lt;string&gt;,这是一种承诺,它将在未来返回string,等待这个字符串结果你可以使用关键字await,但要使用它,你的方法应该有@ 987654326@关键字。

    或者你可以使用这个方法selectName的同步版本,如果它也是WCF生成的,代码会是这样的:

    private void btnSignIn_Click_1(object sender, RoutedEventArgs e)
    {
        Login._name = ServiceClientObj.selectName(int.Parse(studentIdBox.Text));
        Frame.Navigate(typeof(WelcomePage));
    }
    

    【讨论】:

    • 谢谢,我在服务客户端对象之前添加了'await'并且工作正常!你提到的同步方法我没有尝试过,但是我想问一下它与异步方法相比有什么不同?
    猜你喜欢
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 1970-01-01
    相关资源
    最近更新 更多