c# - 单根类层次结构的优点

标签 c# java .net oop object

我想了解 .NET、Java 等语言中单根类(对象)层次结构的所有优点。

我能想到一个优势。假设我有一个函数,我想接受所有数据类型(或其引用)。那么在那种情况下,我可以编写一个函数,而不是为每种数据类型编写一个函数:

public void MyFun(object obj)
{
     // Some code
}

我们从这种类型的层次结构中获得了哪些其他优势?

最佳答案

我将引用一本好书中的一些台词 - Thinking in Java通过 Bruce Eckel :


All objects in a singly rooted hierarchy have an interface in common, so they are all ultimately the same type. The alternative (provided by C++) is that you don’t know that everything is the same fundamental type. From a backward-compatibility standpoint this fits the model of C better and can be thought of as less restrictive, but when you want to do full-on object-oriented programming you must then build your own hierarchy to provide the same convenience that’s built into other OOP languages. And in any new class library you acquire, some other incompatible interface will be used. It requires effort (and possibly multiple inheritance) to work the new interface into your design. Is the extra “flexibility” of C++ worth it? If you need it—if you have a large investment in C—it’s quite valuable. If you’re starting from scratch, other alternatives such as Java can often be more productive.


All objects in a singly rooted hierarchy (such as Java provides) can be guaranteed to have certain functionality. You know you can perform certain basic operations on every object in your system. A singly rooted hierarchy, along with creating all objects on the heap, greatly simplifies argument passing.


A singly rooted hierarchy makes it much easier to implement a garbage collector (which is conveniently built into Java). The necessary support can be installed in the base class, and the garbage collector can thus send the appropriate messages to every object in the system. Without a singly rooted hierarchy and a system to manipulate an object via a reference, it is difficult to implement a garbage collector.


Since run-time type information is guaranteed to be in all objects, you’ll never end up with an object whose type you cannot determine. This is especially important with system level operations, such as exception handling, and to allow greater flexibility in programming.


关于c# - 单根类层次结构的优点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8669693/

相关文章:

java - 使用Javamail连接到Gmail SMTP服务器忽略了指定的端口,并尝试使用25

.net - 如果字符串包含多个值

c# - 查找 System.AccessViolationException 的原因

c# - EF Core 迁移不会获取所有属性

c# - ASP.NET Core 标识 userManager.AddToRoleAsync() - 通过 id 添加

Java 添加到 arraylist 会覆盖其他值

c# - 如何使用apache.commons.codec Base64在Java客户端中解密字符串(在.NET中加密)?

c# - 克隆对象的动机

c# 来自位图数据的 RGB 值

java - String n = new String( char + int) 添加但应该连接