c# - 为什么一个别名的 C# 类型不能被另一个访问?

标签 c# .net alias

好东西

// ok to alias a List Type
using AliasStringList = System.Collections.Generic.List<string>;

// and ok to alias a List of Lists like this
using AliasListOfStringList1 = System.Collections.Generic.List<System.Collections.Generic.List<string>>;

坏东西

// However **error** to alias another alias
using AliasListOfStringList2 = System.Collections.Generic.List<AliasStringList>;

产生编译错误

The type or namespace name 'AliasStringList' could not be found (are you missing a using directive or an assembly reference?)

注意:这是using directive不是 using statement .

最佳答案

您不能在另一个 using 中使用在 using 中声明的别名。对于像您这样的一组 usings,您可以假设兄弟 using 声明不存在。

From MSDN

The order in which using-alias-directives are written has no significance, and resolution of the namespace-or-type-name referenced by a using-alias-directive is not affected by the using-alias-directive itself or by other using-directives in the immediately containing compilation unit or namespace body. In other words, the namespace-or-type-name of a using-alias-directive is resolved as if the immediately containing compilation unit or namespace body had no using-directives

它提供了您确切问题的简化示例,这是预期的行为:

namespace N1.N2 {}
namespace N3
{
   using R1 = N1;         // OK
   using R2 = N1.N2;      // OK
   using R3 = R1.N2;      // Error, R1 unknown
}

关于c# - 为什么一个别名的 C# 类型不能被另一个访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2429829/

相关文章:

c# - 从字符串 EOT 逗号 ETX 中删除控制字符序列

c# - 使用二进制列作为比较标准

c# - 检查 ArrayList 中是否存在任何值的最佳方法

c# - 使用 Wpf .NET 6 和 CommunityToolkit.Mvvm 包显示 ObservableGroupedCollection<string, TElement> 的正确方法

.net - 当启动时发生错误时,如何在显示 MessageBox 后立即退出 Windows 窗体应用程序?

SQL语法新手学生

c# - ID 的 Crystal 报表

c# - BitmapSource 到 BitmapImage

java - 如何在 Java 中创建一些变量类型别名

permissions - Yii Framework : Alias "application.extensions.langhandler.ElangHandler" is invalid. 确保它指向现有的 PHP 文件