【问题标题】:Variable assignment that updates reference?更新引用的变量赋值?
【发布时间】:2016-12-18 18:59:03
【问题描述】:

我搜索了很多,但没有找到答案。

这就是我所拥有的:

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 语句

我的班级不仅仅是 2 个 Wrapper,而且我的类型不仅仅是 'Wrapper'。

谢谢

【问题讨论】:

  • 声明字段时只需初始化即可。
  • 可以等一下C# 7吗?
  • 如果你有“多于”两个包装器,也许它们应该在字典中,而不是每个实例有一个字段。

标签: c# reference pass-by-reference variable-assignment


【解决方案1】:

没有办法完全按照您的要求进行操作。

但是,添加到 Blorgbeard 的评论中,您可以使用字典:

using System.Collections.Concurrent;

ConcurrentDictionary<int, Wrapper> wrapperDictionary;

public Wrapper GetWrapper(int num)
{
    return wrapperDictionary.GetOrAdd(num, _ => new Wrapper());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-26
    • 2021-08-28
    相关资源
    最近更新 更多