C# 必须在退出时指定参数
我正在尝试使用C# 必须在退出时指定参数,c#,C#,我正在尝试使用ConcurrentDictionary的TryRemove with lambda out如何获得错误消息退出时必须分配参数 代码: 为什么? 因为我觉得这个代码有点难看 代码: Reminder rm; _reminders.TryRemove(identifier, out rm); rm.Cancel(); 我能想到的最好的扩展方法如下: static void TryRemoveAndPerformAction<TKey, TValue>( this
ConcurrentDictionary
的TryRemove with lambda out如何获得错误消息退出时必须分配参数
代码:
为什么?
因为我觉得这个代码有点难看
代码:
Reminder rm;
_reminders.TryRemove(identifier, out rm);
rm.Cancel();
我能想到的最好的扩展方法如下:
static void TryRemoveAndPerformAction<TKey, TValue>(
this ConcurrentDictionary<TKey, TValue> dict,
TKey key, Action<TValue> action)
{
TValue value;
if (dict.TryRemove(key, out value)) action(value);
}
_reminders.TryRemoveAndPerformAction(identifier, rm => rm.Cancel());
,使用或参数修饰符声明的方法参数通过引用传递,而不是通过值传递。这允许被调用的方法更改调用方作用域中的值
不同之处在于,使用ref
声明的参数可以在从方法返回之前分配一个值,但是使用out
声明的参数必须在从方法返回之前分配一个值 两种代码替代方案都不起作用。第一个至少有两个编译问题,如果rm
为null,第二个将失败。@递归否此处不会失败。@DanielEugen尝试传入字典中没有的标识符,您将在rm.Cencel()
上得到一个null引用异常。您的编辑似乎有效,但我投票反对,因为它改变了意思。当然,如果您愿意,您仍然应该使用该代码。
_reminders.TryRemoveAndPerformAction(identifier, rm => rm.Cancel());