Tân*_*Tân 2 .net c# recursion func async-await
我想声明一个匿名方法来获取新的主题ID.一切都很好,除了await这个重新运行的匿名方法.
我的测试代码:
public async Task<int> AddNewTopic()
{
using (var db = new MyDatabase()) //EF
{
Func<Task<string>> id = async () =>
{
var random = new Random();
var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
.ToCharArray();
string _id = string.Empty;
for (byte i = 0; i < 32; i++)
{
_id += chars[random.Next(0, chars.Length)].ToString();
}
bool isExist = await db.Topics.SingleOrDefaultAsync(m => m.Id == _id) != null;
//if this id already exists, try again...
return !isExist ? _id : await id(); //error: Use of unassigned local variable id
//I've tried:
//return ""; //That's okay. No problem here.
};
//do stuff...
}
}
Run Code Online (Sandbox Code Playgroud)
它抛出了一条错误信息await id():
使用未分配的局部变量id
为什么Func需要之前分配?我不认为这是这种情况:
int a;
int b = a; //Use of unassigned local variable a
Run Code Online (Sandbox Code Playgroud)
此外,doc没有说Func需要默认值.
你能解释一下为什么吗?
你正在使用它的声明变量.通过在声明上指定null可以解决该问题.
Func<Task<string>> id = null;
id = async () =>
{
...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1126 次 |
| 最近记录: |