如何从抽象类创建对象?
我们知道c#中的Array类是抽象的。
但该类的静态CreateInstance方法返回Array类的对象。
怎么可能呢?
We know that the Array class in c# is abstract.
But the static CreateInstance method of this class returns an object of the Array class.
How is it possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
描述
不,您不能创建抽象类的实例。
更多信息
Description
No, you cant create an instance of an abstract class.
More Information
它是一个返回数组实例的静态工厂方法。此示例为整数值类型创建一个长度为 10 的数组。
这应该为您提供更多详细信息 http://msdn.microsoft.com/en-我们/library/zb3cfh7k.aspx
It's a static factory method that returns an instance of array. this example creates an array of length 10 for integer value types.
This should give you some more detail http://msdn.microsoft.com/en-us/library/zb3cfh7k.aspx
方法
Array.CreateInstance()
的各种重载被类型化为返回Array
,这确实是一个抽象类。但它们返回的对象类型并不是直接Array
,而是Array
继承的某种类型(具体类型取决于所使用的重载)以及您传入的参数)。例如:
基本上和下面的工厂方法原理是一样的:
这里,
Animal
是一个抽象基类型,Cat
和Dog
是具体的从Animal
和animalType
继承的类型告诉我们该方法应返回哪种类型。现在,.Net 中对数组进行了多种特殊处理(例如,有专门处理数组的 IL 指令)。但它们在类型系统中并不是例外(也许数组协变除外)。
The various overloads of the method
Array.CreateInstance()
are typed as returningArray
, which indeed is an abstract class. But the type of the object they return is not directlyArray
, it's some type that inherits fromArray
(what type exactly depends on the overload used and the parameters you pass in).For example:
Basically, it's the same principle like the following factory method:
Here,
Animal
is an abstract base type,Cat
andDog
are concrete types that inherit fromAnimal
andanimalType
tells us which type should the method return.Now, arrays are treated specially in several ways in .Net (for example, there are IL instructions specifically for dealing with arrays). But they are not an exception in the type system (except, maybe for array covariance).
Array
似乎是抽象类的一个特例。根据我在 文档 中读到的内容,我建议数组的创建和函数以某种方式在 .NET Framework 代码中进行内部处理 - 最有可能广泛使用本机代码以获得更好的性能结果。我认为这就是为什么这个类被抽象的原因。如果更了解 .NET Framework 内部结构的人可以改进我的答案,我会很高兴。
Array
seems to be a special case of abstract class. From what I've read in Documentation I'd suggest thatArray
creation and functions are somehow handled internally in .NET Framework code - most probably extensively using native code for better performance results. I think that's why this class have been made abstract.I'd be glad if someone more knowledgable of .NET Framework internals can improve my answer.
我认为解决这种情况的最佳方法是考虑一种返回接口实例的方法!
好吧,您知道我们不能创建接口的实例,但在内部,方法可能知道实现该接口的类并返回该类的实例。
I think the best way to relate to this situation is by considering a method that returns you instance of an interface!!!
Well, you know that we can not create instance of an interface, but internally a method may know about a class implementing that interface and return instance of that class.
你可以这样做
You can do like this