实例与对象。 class原理的抽象实例?

Instance vs Object. Instance of an abstract class principle?

我看过一本书:

At the top of the character stream hierarchy are the abstract classes TextReader and TextWriter.

同一本书中说:

it is not possible to create an object of abstract class, we can use it only through inherited class which overrides the abstract .

但是 Console.InTextReader 实例 。如何从 abstract class 创建实例?有人可以解释一下吗? instanceobject.

有什么区别

好的,让我们来看看 Console.In - 在我的系统(现在是 Mono 4)上 运行 时间它的类型是:

Console.In.GetType()
{System.IO.CStreamReader}

(这是直接来自-window - 我留下了其他东西;))

所以即使staticSystem.Consoleclass的属性InTextReader类型,它的实际值也可以当然是 TextReader 的任何派生 class(因此 CStreamReader 必须以某种方式从 TextReader 派生)。

这基本上就是继承背后的 魔法 - 你可以编写适用于 any TextReader 的代码,即使你永远不能直接创建其中之一。

顺便说一下,您不必考虑 抽象 classes 来实现这一点 - 只需考虑 接口 - 从某种意义上说,这些是最抽象的 things (因为在 .NET 中它们不能只包含 abstract 成员) - 你不能实例化一个直接接口 - 但您当然可以提供 class 实现它的对象。

示范[​​=44=]

遗憾的是你不能 set Console.In 属性 因为它是只读的(而且我不想使用一些反射魔法)所以我不得不创建我自己的 MyConsole):

static class MyConsole 
{
    public static System.IO.TextReader In { get; set; }

    public static string ReadLine()
    {
        return In.ReadLine ();
    }

    public static void WriteLine(string line)
    {
        Console.WriteLine (line);
    }
}

但在这里您可以看到您现在可以设置 .In 属性 并且它将使用 StringReader 实例:

var reader = new System.IO.StringReader ("Hello you\nwhat's up");
MyConsole.In = reader;
var l1 = MyConsole.ReadLine ();
MyConsole.WriteLine (l1);
var l2 = MyConsole.ReadLine ();
MyConsole.WriteLine (l2);

尝试一下 - 您会看到它读取 "Hello you""what's up" 行并将它们打印出来。

What is the difference between instance and object ?

实例是内存中的一个对象。基本上你创建对象并在使用它们时实例化它们。

But Console.In is an instance of TextReader.

如果你这样做

  Type res = Console.In.GetType();

并检查它。然后你会得到类似

的东西

注意这里的基数是 SynctextReader 派生自 TextReader.

C# 中的声明类似于:

namespace System.IO
{
   public class TextReader
   {
      class SyncTextReader : TextReader
      {
      }
   }
}

所以 Console.In 不是 textReader 的实例,而是属于 SyncTextReader

叫做Polymorphism。您看到的 "TextReader" 对象的 class 名称是 Console.in,因为 Console.in 继承自 TextReader

回答你的问题 "What is the difference between instance vs object" 请see this explanation。我知道这个 link 与 Java 相关,但它应该可以帮助您理解这些概念。