是否可以消除使用声明中冲突类型名称的歧义?

时间:2012-02-24 08:46:38

标签: c# .net compiler-construction namespaces collision

例如,System.ThreadingSystem.Timers都有类Timer。因此,如果我想在使用System.Timers.Timer的类中使用System.Threading,我必须使用

之类的内容
System.Timers.Timer myTimer = new System.Timers.Timer();

每次我想声明/初始化计时器。有没有办法告诉编译器“每当我说Timer时,除非另有说明,否则使用System.Timers.Timer?”这样我就可以使用简单的

Timer t = new Timer();

在默认情况下表示System.Timers.Timer,除非我明确指定

System.Threading.Timer t2 = new System.Threading.Timer();

3 个答案:

答案 0 :(得分:5)

您可以为类型(或命名空间)创建别名。见using Directive (MSDN)

using TimersTimer = System.Timers.Timer;

....

var myTimer = new TimersTimer();

答案 1 :(得分:4)

using System.Threading;
using System.Timers;
using Timer = System.Timers.Timer;

现在Timer引用System.Timers.Timer,但任何来自任一命名空间的其他内容仍然可用而没有前缀。

答案 2 :(得分:0)

请参阅The using Directive

using MyAlias = System.Timers.Timer;
var foo = new MyAlias();