gpt4 book ai didi

c# - 在匿名方法中命名参数

转载 作者:太空宇宙 更新时间:2023-11-03 19:54:58 27 4
gpt4 key购买 nike

我正在创建一个匿名方法来生成随机字符串。

在声明该方法之前,我没有声明任何名为id 的参数。但是我仍然无法在方法中定义 string id = string.Empty;

// No parameter within name `id` here...

Func<Task<string>> getIdAsync = null;
getIdAsync = async () =>
{
// string id = string.Empty; // error here. try to use `_id` instead of `id`
string _id = string.Empty;

// logic...

return _id;
};

// _id = ""; // we cann't re-use `_id` here, but `_id` can use `id` below

// `id` is declared after the method
string id = await getIdAsync();

也许我误解了,但我认为它应该在以下情况下抛出错误(仅在这种情况下):

// declare `id` before
string id = string.Empty;

Func<Task<string>> getIdAsync = null;
getIdAsync = async () =>
{
/*
* A local or parameter named 'id' cannot be declared in this scope
* because that name is used in an enclosing local scope to define a local or parameter
*/
string id = string.Empty;

// logic...
};

id = await getIdAsync();

有人能纠正我吗?

最佳答案

这是正确的。

您正在尝试重新声明变量 id

解决方案取决于您要执行的操作。如果你想设置 id 那么简单地删除类型定义;

getIdAsync = async () =>
{
id = string.Empty;

// logic...
};

但是,这不是一个好的做法,因为 id 可能会被您的异步方法之外的代码覆盖 - 除非您确实想要这样做。如果这只是匿名方法范围内的局部变量,则重命名它:

getIdAsync = async () =>
{
string localId = string.Empty;

// logic...
};

这与在 if 语句或循环中声明同名对象是一样的。

关于c# - 在匿名方法中命名参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34723381/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com