面向对象中如何动态的调用其它的类

来源:互联网 发布:淘宝商城在哪年成立的 编辑:程序博客网 时间:2024/06/05 19:03

问题:

         在一个主程序中调用一个类,假设为类名A,调用这个A的方法,但当用户觉得调用这个A的方法不够准确,于是设计了另一个类,类名为B,B也实现同一个方法名,但实现的具体过程不一样,问题是:能否通过界面化的方式人工设置调用了B类而不是以前的A类了,不用去修改主程序的源代码,A类可能也是存在的,因为它可以作为B类的父类,问题主要在于B类的类名B,是在将来命名的,可以说是随机的,通过什么样的方式能实现这种调用 ?

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ConsoleApplication1
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            
//加载当前的程序集(WindowsApplication1.exe是当前的程序的exe)
            System.Reflection.Assembly ass = System.Reflection.Assembly.LoadFrom("ConsoleApplication1.exe");
            Type[] mytypes 
= ass.GetTypes();//获取程序集的类型
            Console.WriteLine("选择你需要调用的类:");
            
int index = 0;
            
foreach (Type t in mytypes)//列出程序集中的所有类
            {
                
if (t.IsClass)//判断该类型是不是类
                    Console.WriteLine(index + " " + t.Name);
                index
++;
            }

            
int selectIndex = int.Parse(Console.ReadLine());//按照要求,界面化的方式人工设置调用,选择你需要的类
            Type type = mytypes[selectIndex];

            
//创建程序集类型一个实例,as操作符来判断该类是否支持指定的接口,如果不支持将给接口变量赋空值(null)
            IMyInterface myInterface = System.Activator.CreateInstance(type) as IMyInterface;
            
if (myInterface != null)
                Console.Write(
"你所调用函数的返回值是:"+myInterface.getInformation());
            
else
                Console.WriteLine(
"该类不支持指定接口!");
            Console.Read();
        }

    }

    
//编写一个接口,接口里的方法可以由不同的类来继承实现
    public interface IMyInterface
    
{
        
string getInformation();
    }

    
public class A : IMyInterface
    
{
        
public string getInformation()//实现方式一
        {
            
return "A.getInformation()";
        }

    }

    
//类名可以是将来命名,也可以是随机的,需要调用时可以通过反射(Reflection)来获取
    public class B : IMyInterface
    
{
        
public string getInformation()//实现方式二
        {
            
return "B.getInformation()";
        }

    }


}

 

http://topic.csdn.net/u/20071006/15/cf4a9748-af81-4d84-b8b4-c2f38deb923a.html