简体   繁体   中英

Cannot implicitly convert type 'bool' to 'system.threading.tasks.task bool'

I have this error: "Cannot implicitly convert type 'bool' to 'system.threading.tasks.task bool'" in my service implementation code. Could you correct my code please.

public Task<bool> login(string usn, string pwd)
    {
        DataClasses1DataContext auth = new DataClasses1DataContext();
        var message = from p in auth.Users
                      where p.usrName == usn && p.usrPass == pwd
                      select p;
        if (message.Count() > 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

You need to be specific whether you want this operation happen asynchronously or not.

As an example for Async Operation :

public async Task<bool> login(string usn, string pwd)
{
    DataClasses1DataContext auth = new DataClasses1DataContext();
    var message = await (from p in auth.Users
                  where p.usrName == usn && p.usrPass == pwd
                  select p);
    if (message.Count() > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

If you don't need it to be an Async operation, try this:

public bool login(string usn, string pwd)
{
    DataClasses1DataContext auth = new DataClasses1DataContext();
    var message = from p in auth.Users
                  where p.usrName == usn && p.usrPass == pwd
                  select p;
    if (message.Count() > 0)
    {
        return true;
    }
    else
    {
        return false;
    }
}

async and await are compatible with .net 4.5 and C# 5.0 and more asyncawait与.net 4.5和C#5.0及更高版本兼容

If you add Task.FromResult , you can fake it into compiling and working even though your method is not async . I had to do this when hooking up Identity, which is all async , to a legacy back end.

Example:

public override Task<bool> IsEmailConfirmedAsync(string userId)
{
  var profile = UserProfileType.FetchUserProfile(AtlasBusinessObject.ClientId.ToString(), decimal.Parse(userId));
  Task.FromResult(profile.EmailAddress.NullIfEmpty() != null);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM