[英]Return a string value from a DynamoDB table in an async C# method
因為我剛接觸C#,很難理解與此相關的其他問題和答案,所以我希望這不是此處提出的其他問題的完全重復,而我不能利用這些其他問題。
我在DynamoDB中有一個帶有兩列的表: reference
和Value
。 我正在嘗試使用reference
作為分區鍵來獲取“值”列的Value
。 到目前為止,這是我嘗試過的:
public async void GetData(string reference)
{
var data = await _client.GetItemAsync(
"my-data",
new Dictionary<string, AttributeValue>
{
{"reference", new AttributeValue {S = reference}}
}
);
var item = data.Item.Values.First().S;
System.Console.WriteLine(item);
}
我想返回為字符串的item
變量,但是由於該方法是async
我不允許這樣做。 如何從該方法返回字符串?
當方法異步時,您應該返回Task
。 另外,通常應避免從異步方法返回void
。 相反,如果沒有返回值,則返回Task
。 有一個完整的解釋在這里 。
假設您的item
類型為T
,那么通常您從async
方法返回,例如:
public async Task<T> GetData(string reference)
{
var data = await _client.GetItemAsync(
"my-data",
new Dictionary<string, AttributeValue>
{
{"reference", new AttributeValue {S = reference}}
}
);
return data.Item.Values.First().S;
}
因此,如果您的item
是字符串,則應為
public async Task<string> GetData(string reference)
{
var data = await _client.GetItemAsync(
"my-data",
new Dictionary<string, AttributeValue>
{
{"reference", new AttributeValue {S = reference}}
}
);
return data.Item.Values.First().S;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.