日期:2014-05-17  浏览次数:21064 次

如何去遍历接口下的类
假如我有一个接口叫IA,继承它的类有3个活着N个,我怎么去遍历这些类呢?
interface IA{}

class B:IA{}
class C:IA{}
class D: IA{}

我怎么去遍历这些类呢

------解决方案--------------------
用这个就行了,
 List<IA> objectCollection = new List<IA>();
 objectCollection .Add(new B());
 objectCollection .Add(new C());
 objectCollection .Add(new D());

//如是不要它,就去掉
C# code
 objectCollection .Remove(index_intType );

------解决方案--------------------
给你写了一个简单的控制台demo

C# code
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;

namespace ConsoleApplication1
{
    class Program
    {
        public static CompositionContainer Container = new CompositionContainer();
        
        static void Main(string[] args)
        {
            mef_init();
          
            IAFactory Iafactory = new IAFactory();
            //组合IA接口
            Container.ComposeParts(Iafactory);        
            var ias = Iafactory.IAs;
            foreach (var IADemo in ias)
            {
                Console.WriteLine(IADemo.Export());
                
            }
            Console.Read();
        }

        /// <summary>
        /// 初始化MEF设置
        /// </summary>
        private static void mef_init()
        {
            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new DirectoryCatalog(@"."));
            catalog.Catalogs.Add(new AssemblyCatalog(typeof(Program).Assembly));
            Container = new CompositionContainer(catalog);       
        }

    }
    interface IA
    {
        string Export();


    }
    [Export(typeof(IA))]
    class B : IA
    {
        public string Export()
        {
            return "Class=B";
        }


    }
    [Export(typeof(IA))]
    class C : IA
    {
        public string Export()
        {
            return "Class=C";
        }

    }
     [Export(typeof(IA))]
    class D : IA
    {
        public string Export()
        {
            return "Class=" + this.GetType().FullName;
        }

    }


    class IAFactory
    {
     
        [ImportMany(typeof(IA))]
        public IEnumerable<IA> IAs { get; set; }

     
    }


}