使用嵌套的名称空间 [英] Using nested namespaces
本文介绍了使用嵌套的名称空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出以下命名空间结构:
Given the following namespace structures:
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; } } }
为什么我会有以下行为?
Why do I get the following behaviour?
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
指令将允许我在将来的使用中省略该部分.不是吗?
I had believed that using periods in a namespace would have the same effect as nesting it (ie namespace A.A1 { }
== namespace A { namespace A1 { } }
), and that the using
directive would allow me to omit that portion in future uses. Is this not the case?
推荐答案
从使用指令页面:
创建一个using指令以使用命名空间中的类型,而不必指定命名空间. using指令不能使您访问嵌套在您指定的名称空间中的任何名称空间.
你不能做你想做的事.
举一个简单的例子:
using System;
public class Foo
{
public void Bar()
{
// Compilation error!
// You need new System.Collections.Generic.List<int>();
new Collections.Generic.List<int>();
}
}
这篇关于使用嵌套的名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文