简体   繁体   中英

Cannot implicitly convert type 'System.Collections.Generic.List<>' to 'System.Threading.Tasks.Task<>>

I am getting an exception.

Cannot implicitly convert type 'System.Collections.Generic.List<IntegraPay.Domain.SObjects.Industry>' to 'System.Threading.Tasks.Task<System.Collections.Generic.IEnumerable<IntegraPay.Domain.SObjects.Industry>>'

Below is my property and method.

  private List<WebFormFieldContent> WebFormFields { get; set; } = 
       new List<WebFormFieldContent>();

  Task<IEnumerable<WebFormFieldContent>> IRegistrationRepository.GetWebFormFields()
        {
            return WebFormFields;
        }

This error typically happens when you are missing async in the method declaration.

When you put async in the signature, C# compiler adds "magic" to do the conversion from an object to a Task<T> returning that object.

However, in your situation async is unnecessary, because you return a task with a result that you already have:

return Task.FromResult<IEnumerable<WebFormFieldContent>>(
    WebFormFields
);

Your method return type is

Task<IEnumerable<WebFormFieldContent>> 

but the implementation returns a

List<WebFormFieldContent>. 

You can change it to

Task<List<WebFormFieldContent>> IRegistrationRepository.GetWebFormFields()
    {
        return Task.FromResult(WebFormFields);
    }

Or change the private variable to

IEnumerable<WebFormFieldContent> WebFormFields { get; set; } = 
   new List<WebFormFieldContent>();

type.

Or you can add an async key word to make it a synchronous call

async Task<IEnumerable<WebFormFieldContent>> IRegistrationRepository.GetWebFormFields()
    {
        return WebFormFields;
    }

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