【问题标题】:C# Nested Type Aliases - Cannot Resolve SymbolC# 嵌套类型别名 - 无法解析符号
【发布时间】:2020-12-31 03:07:49
【问题描述】:

为什么这不能在 Unity 2018 C# 中编译?

namespace MyNS
{
    using FooTable = Dictionary<int, float[]>;
    using BarTable = Dictionary<int, FooTable>;
} 

同样,如果我省略命名空间:

using FooTable = System.Collections.Generic.Dictionary<int, float[]>;
using BarTable = System.Collections.Generic.Dictionary<int, FooTable>;

我得到同样的编译器错误。

(坦率地说,我不知道为什么 Dictionary 限定符在命名空间内是可选的,但在外部是强制性的!)

编译器错误是针对using BarTable... 行中的最后一个符号:“无法解析符号FooTable”。

这种方式不能嵌套类型别名吗?

【问题讨论】:

  • "我不知道为什么 Dictionary 限定符在命名空间内是可选的,但在外部是强制性的" - 因为 inside namespace 语句编译器至少知道“外部”命名空间被导入,而“外部”则没有。
  • @Dai 啊,如果我在同一个文件中声明两个命名空间会怎样?两个命名空间会获得相同的一组导入命名空间吗?让我想知道为什么顶级 using 声明不是 inside 命名空间虽然...
  • 正确,您可以在同一个 *.cs 文件中拥有多个 namespace 块 - 是的,它们都将“继承”相同的导入“外部”命名空间,但它们不共享“内部”导入的命名空间。

标签: c# unity3d using type-alias


【解决方案1】:

编译器不允许这样做:

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-directive#remarks

创建一个 using alias 指令,以便更容易地限定一个 命名空间或类型的标识符。在任何 using 指令中, 无论使用什么,都必须使用完全限定的命名空间或类型 之前的指令。不能使用 using 别名 using 指令的声明。例如,以下生成 编译器错误:

using s = System.Text;
using s.RegularExpressions; // Generates a compiler error.

【讨论】:

  • 那么有没有办法创建嵌套类型别名?如果我最终得到具有多种类型的分层结构,例如Dictionary&lt;Foo, Dictionary&lt;Bar, Dictionary&lt;Baz, Dictionary&lt;Fuz, int&gt;&gt;&gt;&gt;,该怎么办?我是否辞职将每个子类型复制/粘贴到任何地方?我正在寻找 C++ 中的 usingtypedef 关键字。
猜你喜欢
  • 1970-01-01
  • 2017-05-26
  • 2015-07-22
  • 2021-02-04
  • 2011-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多