更新引用的变量赋值?
Variable assignment that updates reference?
我搜索了很多,但没有找到答案。
这是我的:
Wrapper _wrap1;
Wrapper _wrap2;
public Wrapper GetWrapper(int num)
{
Wrapper cachedWrapper = num == 1 ? _wrap1 : _wrap2;
if(cachedWrapper == null)
{
cachedWrapper = new Wrapper();
}
return cachedWrapper;
}
我知道“cachedWrapper
”是一个新引用,对 _wrap1
或 _wrap2
都没有影响。
我正在寻找一种优雅的方式来更新这些字段而不需要额外的 if 语句。
我的 class 不仅仅是 2 个包装器,我的类型也不仅仅是 'Wrapper'。
谢谢
没有办法准确地满足您的要求。
但是,添加到 Blorgbeard 的评论中,您可以使用字典:
using System.Collections.Concurrent;
ConcurrentDictionary<int, Wrapper> wrapperDictionary;
public Wrapper GetWrapper(int num)
{
return wrapperDictionary.GetOrAdd(num, _ => new Wrapper());
}
我搜索了很多,但没有找到答案。
这是我的:
Wrapper _wrap1;
Wrapper _wrap2;
public Wrapper GetWrapper(int num)
{
Wrapper cachedWrapper = num == 1 ? _wrap1 : _wrap2;
if(cachedWrapper == null)
{
cachedWrapper = new Wrapper();
}
return cachedWrapper;
}
我知道“cachedWrapper
”是一个新引用,对 _wrap1
或 _wrap2
都没有影响。
我正在寻找一种优雅的方式来更新这些字段而不需要额外的 if 语句。
我的 class 不仅仅是 2 个包装器,我的类型也不仅仅是 'Wrapper'。
谢谢
没有办法准确地满足您的要求。
但是,添加到 Blorgbeard 的评论中,您可以使用字典:
using System.Collections.Concurrent;
ConcurrentDictionary<int, Wrapper> wrapperDictionary;
public Wrapper GetWrapper(int num)
{
return wrapperDictionary.GetOrAdd(num, _ => new Wrapper());
}