C# 更新引用的变量赋值?
我找了不少,但没有找到答案 这就是我所拥有的:C# 更新引用的变量赋值?,c#,reference,pass-by-reference,variable-assignment,C#,Reference,Pass By Reference,Variable Assignment,我找了不少,但没有找到答案 这就是我所拥有的: Wrapper _wrap1; Wrapper _wrap2; public Wrapper GetWrapper(int num) { Wrapper cachedWrapper = num == 1 ? _wrap1 : _wrap2; if(cachedWrapper == null) { cachedWrapper = new Wrapper(); } return cachedW
Wrapper _wrap1;
Wrapper _wrap2;
public Wrapper GetWrapper(int num)
{
Wrapper cachedWrapper = num == 1 ? _wrap1 : _wrap2;
if(cachedWrapper == null)
{
cachedWrapper = new Wrapper();
}
return cachedWrapper;
}
我知道“cachedWrapper
”是一个新的参考,对\u wrap1
或\u wrap2
都没有影响
我正在寻找一种优雅的方式来更新这些字段,而不需要额外的if语句
我的类不仅仅有两个包装器,我的类型也不仅仅是“包装器”
谢谢没有一种方法可以精确地满足你的要求 但是,除了Blorgbeard的评论之外,你还可以使用字典:
using System.Collections.Concurrent;
ConcurrentDictionary<int, Wrapper> wrapperDictionary;
public Wrapper GetWrapper(int num)
{
return wrapperDictionary.GetOrAdd(num, _ => new Wrapper());
}
使用System.Collections.Concurrent;
ConcurrentDictionary-wrapperDictionary;
公共包装器GetWrapper(int num)
{
返回wrapperDictionary.GetOrAdd(num,=>newwrapper());
}
没有一种方法可以精确地满足您的要求
但是,除了Blorgbeard的评论之外,你还可以使用字典:
using System.Collections.Concurrent;
ConcurrentDictionary<int, Wrapper> wrapperDictionary;
public Wrapper GetWrapper(int num)
{
return wrapperDictionary.GetOrAdd(num, _ => new Wrapper());
}
使用System.Collections.Concurrent;
ConcurrentDictionary-wrapperDictionary;
公共包装器GetWrapper(int num)
{
返回wrapperDictionary.GetOrAdd(num,=>newwrapper());
}
在声明字段时只需初始化字段。您可以等待吗?如果您有“更多”两个包装,那么它们可能应该在字典中,而不是每个实例有一个字段。在声明字段时只需初始化字段。您可以等待吗?如果您有“更多”两个包装,那么它们可能应该在字典中,而不是每个实例有一个字段。