[英]In C# are the `using` directives of the base class inherited by the child class?
Let's say we have a base class Rectangle
and a derived class Square
: 假设我们有一个基类
Rectangle
和一个派生类Square
:
namespace Shapes {
using System.Foo;
public class Rectangle {
public Rectangle(int l, int w){}
}
}
namespace Shapes {
public class Square : Rectangle
public Square(int l, int w){}
}
Does the Square
class have to explicitly say that it is using System.Foo
? Square
类是否必须明确说它正在使用System.Foo
? I'm getting erratic results. 我的结果变得不稳定了。 In one project the
using
directives seem to be inherited and in a web application they aren't. 在一个项目中,
using
指令似乎是继承的,而在Web应用程序中则不是。
using
statements, in this context, don't compile to code -- they are helpers to make your code read cleaner for others. 在这种情况下,
using
语句不会编译成代码 - 它们是帮助您使代码更清晰的帮助程序。 As a result, they are not "inherited". 结果,它们不是“继承”的。
So, to answer your question, your Square
class needs to reference System.Foo
- either with a using
statement, or by using a fully qualified class name. 因此,要回答您的问题,您的
Square
类需要引用System.Foo
- using
语句或使用完全限定的类名。
A using
statement will only propagate to the next set of closing braces ( }
) from the level it was declared on within the same the file. using
语句只会从同一个文件中声明的级别传播到下一组右括号( }
)。
//From File1.cs
using System.Baz;
namespace Example
{
using System.Foo;
//The using statement for Foo and Baz will be in effect here.
partial class Bar
{
//The using statement for Foo and Baz will be in effect here.
}
}
namespace Example
{
//The using statement for Baz will be in effect here but Foo will not.
partial class Bar
{
//The using statement for Baz will be in effect here but Foo will not.
}
}
//From File2.cs
namespace Example
{
//The using statement for Foo and Baz will NOT be in effect here.
partial class Bar
{
//The using statement for Foo and Baz will NOT be in effect here.
}
}
using
directives are only shared if the classes are in the same file and they are not nested in the classes themselves like in your example. 只有当类在同一个文件中时,才会共享
using
指令,并且它们不像示例那样嵌套在类本身中。
For instance: 例如:
using System.Foo;
namespace N
{
class A {}
class B {}
}
If this is all in one file, A
and B
can both use Foo
. 如果这都在一个文件中,
A
和B
都可以使用Foo
。
using System.Foo;
namespace Shapes {...
Importing should always be top most and not within a namespace. 导入应始终是最重要的,而不是在命名空间内。 This will allow the entire structure of the class to rely on that import when needed.
这将允许类的整个结构在需要时依赖于该导入。
I think everyone is missing the point when it comes to using directives. 我认为每个人在使用指令时都忽略了这一点。 They really have nothing to do with the class at all.
他们真的与班级毫无关系。 using directives in a code file (.cs, .vb, etc...) are not part of the classes defined within the file.
在代码文件中使用指令 (.cs,.vb等...)不是文件中定义的类的一部分。 They are used by the compiler to resolve namespaces when compiling.
编译时,编译器使用它们来解析命名空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.