C#使用别名作为类型参数,其他使用别名 [英] C# using alias as type parameter in other using alias

查看:428
本文介绍了C#使用别名作为类型参数,其他使用别名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在C#程序的顶部定义一对类型别名。这是我要执行的操作的简短示例:

I'm trying to define a pair of type aliases at the top of my C# program. This is a short example of what I'm trying to do:

using System;
using System.Collections.Generic;

namespace Foo {
    using TsvEntry = Dictionary<string, string>;
    using Tsv = List<TsvEntry>;
}

当我尝试使用mcs 3.2.8.0进行编译时,得到以下内容错误消息:

When I try to compile this using mcs 3.2.8.0, I get the following error message:

foo.cs(6,19): error CS0246: The type or namespace name `TsvEntry' could not be found. Are you missing an assembly reference?

是否可以在中使用别名C#中的其他别名,还是我丢失了使用语句的工作方式?

Is it possible to use using aliases within other aliases in C#, or am I missing something about the way using statements work?

推荐答案

检查有关此问题的文档:

Check documentation for this question:

https://msdn.microsoft.com/zh-CN/library/aa664765(v = vs.71).aspx

它说:


使用alias-alias指令的写入顺序没有
的重要性,并且 using-alias-directive引用的
命名空间或类型名称的解析不受

using-alias-directive的影响
立即包含编译单元或命名空间正文中的其他使用指令本身。换句话说,using-alias伪指令的命名空间或类型名称是
解析的,就好像直接包含的编译单元或
命名空间主体没有using伪指令。在示例中

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. In the example

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

a中最后一个使用别名指令的结果编译时错误,因为
不受第一个using-alias-directive的影响。

the last using-alias-directive results in a compile-time error because it is not affected by the first using-alias-directive.

从技术上讲,您不能在相同的名称空间中使用它,但是如果您在名称空间1中使用别名,并在嵌套中为此别名使用别名命名空间,它将起作用:

Technically, you cannot do it same namespace, but if you do alias in namespace 1, and do alias for this alias in a nested namespace, it will work:

namespace N1
{
    namespace N12 { }
}

namespace N2
{
    using R1 = N1;

    namespace N2
    {
        using R2 = R1.N12;
    }
}

我不确定您是否应该使用别名例如,考虑尽可能少地使用它们,主要是为了解决名称空间冲突。

I am not really sure it's worth using aliases in your specific example, consider using them as rare as you can, mostly for resolving namespace conflicts.

这篇关于C#使用别名作为类型参数,其他使用别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆