【发布时间】:2015-07-21 18:45:22
【问题描述】:
给定以下命名空间结构:
namespace A { public static class MyClass { public static int MyInt; } }
namespace A.A1 { public static class MyClass { public static int MyInt; } }
namespace B { namespace B1 { public static class MyClass { public static int MyInt; } } }
为什么会出现以下行为?
namespace C {
using A;
using B;
public class SomeClass {
public void foo() {
// Valid, but renders 'using' directives obsolete
A.A1.MyClass.MyInt = 5;
B.B1.MyClass.MyInt = 5;
// Error: The type or namespace A1/B1 could not be found.
A1.MyClass.MyInt = 5;
B1.MyClass.MyInt = 5;
}
}
}
namespace D {
using A.A1;
using B.B1;
public class SomeClass {
public void bar() {
// Valid, but renders 'using' directives obsolete
A.A1.MyClass.MyInt = 5;
B.B1.MyClass.MyInt = 5;
// Error: MyClass is ambiguous (of course)
MyClass.MyInt = 5;
// Error: The type or namespace A1/B1 could not be found.
A1.MyClass.MyInt = 5;
}
}
}
我曾相信在命名空间中使用句点与嵌套它具有相同的效果(即namespace A.A1 { } == namespace A { namespace A1 { } }),并且using 指令将允许我在以后的使用中省略该部分。不是这样吗?
【问题讨论】:
-
您对行为的哪个确切部分感到惊讶?
A1.MyClass.MyInt不起作用,我并不感到惊讶——命名空间不能那样工作。感觉就像您同时在问几个方面的问题(A1.MyClass.MyInt 是否应该工作,以及 A 和 B 之间的任何区别)。 -
不,它不是......如果你先
using System;然后new Collections.Generic.List<int>();,你可以清楚地看到它 -
如果您已经在
A命名空间中,A1.MyClass.MyInt会起作用。 -
@Liam 是的,我知道为什么会这样:P
标签: c# .net namespaces