问题描述
我正在尝试在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:
它说:
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#使用别名作为类型参数,其他使用别名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!