【问题标题】:Calling function with ref parameter使用 ref 参数调用函数
【发布时间】:2013-06-11 16:15:21
【问题描述】:

我对使用 ref 参数的函数有疑问。这个函数使用 linq 调用自己,如下所示:

public Champ(tabloidConfigColonne tcc,ref Dictionary<string, Jointure> jointures)
            {
              ...
             sousChamps = lc.ToDictionary(
                            o => o.nom,
                            o => new Champ(o, ref jointures));
             }

出现错误提示 ref 在匿名函数中不可用。

功能齐全

public Champ(tabloidConfigColonne tcc,ref Dictionary<string, Jointure> jointures)
        {
            nom = tcc.champ;
            description = tcc.titre;
            type = tcc.type;
            valeurDefaut = tcc.valeurParDefaut;
            modeEdition=new Template(tcc.editeur, tcc.editeurParam1, tcc.editeurParam2, tcc.editeurParam3);
            if (!string.IsNullOrEmpty(tcc.jointure))
            {
                jointure = jointures[tcc.jointure];
                nomTable = jointure.nomNouvelleTable;
            }

            visu=tcc.visu;
            Groupe=tcc.groupe;
            Id=tcc.nom;

            valideurs = tcc.valideurs;
            Obligatoire = tcc.obligatoire;

            if (tcc.colonnes.Count>0)
            {
                List<tabloidConfigColonne> lc = tcc.colonnes.GetColonnes(visibiliteTools.getFullVisibilite(),false);
                sousChamps = lc.ToDictionary(
                    o => o.nom,
                    o => new Champ(o, ref jointures));
            }
        }

感谢您的帮助。

【问题讨论】:

  • 是的,你不能在匿名函数中使用ref。你明白为什么吗?看起来您首先不应该使用 ref - 这不像您更改 Champ 构造函数中的值。请阅读pobox.com/~skeet/csharp/parameters.html
  • 删除ref,您的代码将编译。您没有分配jointures,因此在您的代码中传递ref 并不重要(对Dictionary 的引用将按值传递,这在您的情况下非常好)。
  • 不确定为什么要使用 ref 作为引用类型传递字典,除非您需要实际更新指向新对象的指针,这是不必要的。
  • 我使用 ref 不复制我的字典。没有它也能正常工作,但这是更好的方法吗?
  • 你不复制字典,你复制参考。

标签: c# ref


【解决方案1】:

我没有足够的代表发表评论,所以...

除非您将在函数内创建该对象的新实例,否则无需将 ref 用于引用类型(对象)。

有关ref 的更多说明,请参阅此 SO 帖子: C# ref is it like a pointer in C/C++ or a reference in C++?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    • 2019-05-07
    • 2015-12-08
    • 1970-01-01
    相关资源
    最近更新 更多