[英]How can I return a string rather than SYSTEM.THREADING.TASK.TASK`1[SYSTEM.STRING] from an async function C#
I have a SQLite database within the Xamarin application I am building which stores and retrieves information about animals.我正在构建的 Xamarin 应用程序中有一个 SQLite 数据库,用于存储和检索有关动物的信息。 One of my SQLite async functions is to get the diet of the animal based upon the animal name passed into this function.
我的 SQLite 异步函数之一是根据传递给此 function 的动物名称获取动物的饮食。 From this function I am trying to return a string which will be the found diet, but at the minute it is is returning the value SYSTEM.THREADING.TASK.TASK`1[SYSTEM.STRING].
从这个 function 我试图返回一个字符串,这将是找到的饮食,但现在它正在返回值 SYSTEM.THREADING.TASK.TASK`1[SYSTEM.STRING]。 I have tried all of my ideas, but nothing is working for this.
我已经尝试了我所有的想法,但没有任何效果。 Any help would be appreciated.
任何帮助,将不胜感激。
Animal class:动物 class:
public class Animal
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
[NotNull]
public string Name { get; set; }
[NotNull]
public string Diet { get; set; }
[NotNull]
public string Markings { get; set; }
[NotNull]
public string Ecosystem { get; set; }
}
} }
SQLite function for retrieving the diet: SQLite function 用于检索饮食:
public async Task<string> getAnimalDiet(string animalName)
{
Animal a = await Database.Table<AnimalInfo>().Where(x => x.Name == animalName).FirstOrDefaultAsync();
return await Task.FromResult(a.Diet);
}
Calling this function within my Xamarin (where it returns SYSTEM.THREADING.TASK.TASK`1[SYSTEM.STRING] not the diet as a string)在我的 Xamarin 中调用这个 function (它返回 SYSTEM.THREADING.TASK.TASK`1[SYSTEM.STRING] 而不是作为字符串的饮食)
void getDiet(List<string> final)
{
List<string> found = new List<string>();
if (final.Count > 0)
{
foreach(string animal in final)
{
found.Add(App.Database.getAnimalDiet(animal).ToString());
}
foreach(string entry in found)
{
NewButtonCreation(entry);
}
}
}
You can replace你可以更换
return await Task.FromResult(a.Diet);
with和
return a.Diet;
for the same result.相同的结果。
Your problem is not with how you wrote getAnimalDiet() but with how you call it, it needs to be awaited:您的问题不在于您如何编写 getAnimalDiet() ,而在于您如何称呼它,需要等待:
//found.Add(App.Database.getAnimalDiet(animal).ToString());
found.Add(await App.Database.getAnimalDiet(animal));
but that means that void getDiet( )
has to become async Task getDiet( )
or async void getDiet( )
但这意味着
void getDiet( )
必须成为async Task getDiet( )
或async void getDiet( )
Prefer async Task
and work your way up.更喜欢
async Task
并按自己的方式工作。 Only toplevel methods and eventhandlers should be async void
.只有顶级方法和事件处理程序应该是
async void
。 Google for the differences and consequences.谷歌的差异和后果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.