在多态性中,使用父类引用变量指向子类对象实例的实际用途是什么? [英] In polymorphism what is the practical use of using a parent class reference variable to point to child class object instance?

查看:163
本文介绍了在多态性中,使用父类引用变量指向子类对象实例的实际用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道使用父类引用变量指向多态中的子类对象实例的实际用法是什么?任何人都可以解决这种实例化解决的一些现实世界问题吗?

Hi, I was wondering what is the practical use of using a parent class reference variable to point to child class object instance in polymorphism? Can anybody elaborate on it with some real world problems that this type of instantiation solves?

推荐答案

考虑以下场景...



我想开发新的IDE。

我将为mySql,oracle等各种数据库提供支持。



现在,我将开发一个界面

Consider following scenario...

I want to develop the new IDE.
I will provide support for various databases like mySql, oracle etc.

Now, I will develop one interface
Interface MyInterface
{
  public int Insert();
  public List<object> Select(); 
}





我会将此接口提供给数据库提供商以统一实施。



数据库提供商不允许我看到他们对这些方法的实现。



所以要访问那些方法是什么我需要创建MyInterface的参考,我将分配DB提供程序类的对象引用。

这样我就可以访问数据库提供程序的方法,而无需查看代码的内部实现。 />


MySql DBProvider ...



I will give this Interface to DB providers for uniform implementation.

DB providers wouldn't allow me to see their implementation of those methods.

So to access those Methods what I need is to create the MyInterface's Reference and I will assign the object reference of the classes of DB provider.
This way I can access the methods of DB providers without seeing their internal implementation of code.

MySql DBProvider...

class MySqlDBProvider : : MyInterface
{
    public override int Insert()
    {
       //here their Insert logic goes
    }
    public override List<Object> Select()
    {
       //here their Select logic goes
    }
}



Oracle DBProvider ...


Oracle DBProvider...

class OracleDBProvider : MyInterface
{
    public override int Insert()
    {
       //here their Insert logic goes
    }
    public override List<Object> Select()
    {
       //here their Select logic goes
    }
}





现在我需要的是......



Now what I need is...

using MyInterfaceNamespace;
using MySqlDBProviderNamespace;
public class MyClass
{
   //here i will create reference of MyInterface
   //and assign Object of Your DB Provider Class.
   MyInterface MyIObj = new MySqlDBProvider();
   MyIObj.Insert();
   MyIObj.Select();

   //I can do the same for Oracle
}





希望您了解此功能在此类情况下的重要性。



希望这个帮助

-----------------

Pratik Bhuva



Hope You Understand the importance of this feature in this kind of scenario.

Hope This Help
-----------------
Pratik Bhuva


检查以下示例:



http://msdn.microsoft.com/en-us/library/ms173152.aspx [ ^ ]



http://www.tutorialspoint.com/csharp/csharp_polymorphism.htm [ ^ ]



希望它有所帮助。



Azee ......
Check these examples:

http://msdn.microsoft.com/en-us/library/ms173152.aspx[^]

http://www.tutorialspoint.com/csharp/csharp_polymorphism.htm[^]

Hope it helps.

Azee...


这篇关于在多态性中,使用父类引用变量指向子类对象实例的实际用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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