从类继承
在C#中,你可以继承多少个类?
当你写:
使用 System.Web.UI;
这是否被认为是从类继承?
In C#, how many classes can you inherit from?
When you write:
using System.Web.UI;
is that considered inheriting from a class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
using 指令:
仅意味着如果标识符不在本地命名空间中,则还将在命名空间
XYZ
中搜索该标识符。这允许您拥有更简洁的代码,因此如果您using System.IO.Path
,则不必执行System.IO.Path.Combine()
,例如。我认为您可以拥有的using
语句数量没有限制。C# 不允许多重继承——只能从一个类继承。但是,您可以根据需要实现任意数量的接口。
A using directive:
only means that if an identifier isn't in the local namespace, the namespace
X.Y.Z
will be searched for that identifier as well. This allows you to have somewhat terser code, so you don't have to doSystem.IO.Path.Combine()
if you haveusing System.IO.Path
, for instance. I don't believe there is a limit on how manyusing
statements you can have.C# does not allow multiple inheritance -- you can only inherit from one class. However, you can implement as many interfaces as you'd like.
不,
使用 指令
允许您在向代码添加控件或类时不必键入完全限定的命名空间。
例如,如果我添加:
那么我可以简单地写:
而不是:
继承
您只能从一个类继承,但您可以根据需要实现任意多个接口。
如果我的所有页面都继承自一个基类,那么该基类将需要继承
Page
类才能发挥作用。No,
A
using
directive allows you to not have to type the fully qualified namespace when you add a control or a class to your code.For instance, if I add:
Then I can simply write:
Instead of:
Inheritance
You can only inherit from one class, but you can implement as many Interfaces as you want.
If all of my pages inherit from a base class, then that base class will need to inherit from the
Page
class for it to do any good.您只能从一个类继承。
编写“using System.Web.UI”与继承无关。
该语句仅意味着您想要“使用”命名空间 System.Web.UI 中的类,以便您可以直接编写类名,而不是让它以命名空间名称为前缀。
You can inherit from only one class.
Writing 'using System.Web.UI' has nothing to do with inheritance.
This statement just means that you want to 'use' the classes that are in the namespace System.Web.UI, so that you can directly write the class-name, instead of having it to prefix with the namespace-name.
否。
using
使外部定义的类可见class Cat : Animal
定义了一个派生(继承)自Animal
的类Pet
>C# 与 C++ 不同,不支持多重继承,因此只能从一个类派生(但是,可以实现任意数量的接口)
No.
using
makes externally defined classes visibleclass Cat : Animal
defines a classPet
that derives (inherits) fromAnimal
C#, unlike C++, does not support multiple inheritance, therefore you can only derive it from one class (However, you can implement any number of interfaces)
我想对 Jen 给出的答案添加一个附录。确实,C# 不支持多重继承,但了解可以通过忽略 CLS(命令语言子系统)在 .NET 中实现多重继承会很有用。这是一项令人讨厌的工作,并且需要你滚动自己的虚拟表,但这是可能的。
I'd like to add an addendum to the answer given by Jen. It's correct to say that C# doesn't support multiple inheritance, but it can be useful to know that you can implement multiple inheritance in .NET by ignoring the CLS (the Command Language Subsystem). It's nasty work, and involves you rolling your own vtables, but it is possible.