【问题标题】:Nesting aliases in C#在 C# 中嵌套别名
【发布时间】:2011-01-22 16:53:48
【问题描述】:

我在 C# 中看到了很多关于 typedef 问题的答案,我已经使用过,所以我有:

using Foo = System.Collections.Generic.Queue<Bar>;

这很好用。我可以更改定义(尤其是更改 Bar => Zoo 等)并且使用 Foo 的所有内容都会更改。太好了。

现在我想让它工作:

using Foo = System.Collections.Generic.Queue<Bar>;
using FooMap = System.Collections.Generic.Dictionary<char, Foo>;

但 C# 似乎不喜欢第二行中的 Foo,尽管我已经在第一行中定义了它。

有没有办法将现有别名用作另一个别名的一部分?

编辑:我正在使用 VS2008

【问题讨论】:

  • 同意 Codesleuth - 如果 Foo 是简单类型(如 System.Int32)的别名,它仍然会失败,所以我猜这是编译器错误。
  • @Codesleuth @Dan,想评论一下 Dave 的回答吗?

标签: c# alias typedef


【解决方案1】:

根据标准,答案似乎是否定的。来自Section 16.3.1,第 6 段:

1 的顺序 using-alias-directives 写了 没有意义,和决议的 由 a 引用的命名空间或类型名称 using-alias-directive 不受影响 通过 using-alias-directive 本身或 通过其他使用指令 立即包含编译 单元或命名空间主体。

2 在其他 单词,a 的名称空间或类型名称 using-alias-directive 被解析为 如果立即包含 编译单元或命名空间主体有 没有使用指令。

编辑:

我刚刚注意到上面链接中的版本有点过时了。 4th Edition 中相应段落的文本更详细,但仍禁止在其他人中使用别名进行引用。它还包含一个明确说明这一点的示例。

根据您对范围界定和打字强度的需求,您可能会摆脱类似的情况:

class Foo : System.Collections.Generic.Queue<Bar>
{
}

【讨论】:

    【解决方案2】:

    根据https://stackoverflow.com/a/35921944/2505186,这在放置时是可能的
    using Foo = System.Collections.Generic.Queue&lt;Bar&gt;;

    using FooMap = System.Collections.Generic.Dictionary&lt;char, Foo&gt;;
    在不同的命名空间内,在你的情况下可能是

    ----- cs-file -----
    using System; (and others if needed)
    
    using Foo = System.Collections.Generic.Queue<Bar>;
    namespace my_software
    {
      using FooMap = System.Collections.Generic.Dictionary<char, Foo>;
    
      your usual code
    }
    ----- file end -----
    

    然后,您的代码可能会嵌套在一个额外的命名空间中,这对于这个单一目的来说并不是很好。

    【讨论】:

      猜你喜欢
      • 2021-07-09
      • 1970-01-01
      • 2014-02-07
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      • 2011-03-13
      • 1970-01-01
      • 2019-04-01
      相关资源
      最近更新 更多