C# 字典中TryGetValue的Resharper重构模式
我需要不断编写的最麻烦的语法是在字典中惰性地初始化容器,如:C# 字典中TryGetValue的Resharper重构模式,c#,resharper,automated-refactoring,rider,trygetvalue,C#,Resharper,Automated Refactoring,Rider,Trygetvalue,我需要不断编写的最麻烦的语法是在字典中惰性地初始化容器,如: ContainerRecord value; if(!_dictionary.TryGetValue(key,out value)) { value = new ContainerRecord(); _dictionary[key] = value; } //Container is always initialized here 我觉得这是一个微不足道的重构模式: (至少对于显式变量声明和if语句部分) 我知道在较新版
ContainerRecord value;
if(!_dictionary.TryGetValue(key,out value))
{
value = new ContainerRecord();
_dictionary[key] = value;
}
//Container is always initialized here
我觉得这是一个微不足道的重构模式:
(至少对于显式变量声明和if语句部分)
我知道在较新版本的C#中有一些新的语法糖,消除了预先声明变量的需要。不幸的是,我无法在我的环境中访问这些功能,而且在可预见的将来也无法访问
确实出现了一个“检查包含键”重构,它实现了几乎相同的结果,但缺点是查找两次
是否可以通过一些扩展?我想这是一个很常见的情况,它可能已经在某个地方解决了。您可以为此创建一个自定义模式
Type: Identifier Placeholder
Name: value
Type: Expression Placeholder
Name: key
Type: Type Placeholder
Name: type
Type: Expression Placeholder
Name: dict
Expression Type: System.Collections.Generic.IDictionary<,>
$type$ $value$;
if(!$dict$.TryGetValue($key$, out $value$))
{
$value$ = new $type$();
$dict$[$key$] = $value$;
}
替换为TryGetValue
保存
按钮自定义模式
,您可以使用下拉列表在右侧设置新模式的严重性级别。我选择了建议哇,谢谢你的详细回答。我现在使用的是Rider全职,而不是VS中的resharper。我假设VS中的resharper具有相同的设置,但我找不到任何与您在Rider中描述的内容相匹配的内容。你知道这是支持的吗?不幸的是,Rider bug tracker上的相关问题表明,这在Rider上是不可能的。
$type$ $value$ = $dict$[$key$];
$type$ $value$;
if(!$dict$.TryGetValue($key$, out $value$))
{
$value$ = new $type$();
$dict$[$key$] = $value$;
}