泛型是运行时或编译时多态? [英] Is generics runtime or compile time polymorphism?

查看:335
本文介绍了泛型是运行时或编译时多态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读了下面的格式来下的参数多态,但我们可以在一个划分它,无论是运行时或编译时多态?



 公共类堆栈< T> 
{//项目是T型,当我们创建对象
T []项目这是众所周知的;
诠释计数;当我们创建对象
公共牛逼POP()
{
公共无效推送(T项目){...}
//方法流行的类型将决定.. }
}


解决方案

这是一个小的都。为了使用一个泛型类,你必须给它在编译时的类型参数,但是类型参数可以是一个接口或基类的,所以在运行时使用的实际的,具体的对象的类型可能会有所不同。



例如,在这里我有一个堆叠式和下一个代码片段; T> 字段。我选择使用一个接口作为类型参数。这利用参数多态性在编译时。你必须选择哪种类型的参数,你的 _stack 字段将在编译时使用:

 公共接口的IFoo {无效美孚(); } 

公共堆栈<的IFoo> _stack =新的堆栈<的IFoo>();

现在,当这个代码片段其实是跑,我可以用它的类实现<任何对象code>的IFoo ,以及这一决定并没有进行,直至运行时间:

 公共类Foo1:{IFoo的公共无效美孚(){Console.WriteLine(Foo1); }} 

公共类foo2的:{IFoo的公共无效美孚(){Console.WriteLine(foo2的); }}

公共类Foo3:{IFoo的公共无效美孚(){Console.WriteLine(foo2的); }}

_stack.Push(新Foo1());
_stack.Push(新foo2的());
_stack.Push(新Foo3());

这是的亚型多态性,这是用来在运行时。


I read that the following format comes under parametric polymorphism, but can we classify it in one, either runtime or compile time polymorphism?

public class Stack<T>
{  // items are of type T, which is known when we create the object
   T[] items;  
   int count;  
   public void Push(T item)    {...}
   //type of method pop will be decided when we create the object  
   public T Pop() 
   {...} 
 }  

解决方案

It's a little of both. In order to use a generic class, you have to give it a type parameter at compile time, but the type parameter could be of an interface or base class, so the actual, concrete type of the objects used at runtime can vary.

For example, here I have a snippet of code with a Stack<T> field. I've chosen to use an interface as the type parameter. This utilizes parametric polymorphism at compile time. You must choose which type parameter your _stack field will use at compile time:

public interface IFoo { void Foo(); }

public Stack<IFoo> _stack = new Stack<IFoo>();

Now, when this snippet of code is actually run, I can use any object whose class implements IFoo, and that decision doesn't have to be made until run time:

public class Foo1 : IFoo { public void Foo() { Console.WriteLine("Foo1"); } }

public class Foo2 : IFoo { public void Foo() { Console.WriteLine("Foo2"); } }

public class Foo3 : IFoo { public void Foo() { Console.WriteLine("Foo2"); } }

_stack.Push(new Foo1());
_stack.Push(new Foo2());
_stack.Push(new Foo3());

This is an example of subtype polymorphism, which is utilized at run time.

这篇关于泛型是运行时或编译时多态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆