我可以将对象视为从反射实现接口吗?

时间:2015-01-14 12:36:28

标签: c# dll reflection interface

我正在尝试从所有实现接口的DLL加载类型。我希望能够从DLL中获取类型,创建每种类型的实例,然后将每种类型视为实现接口。我已经在下面写了一个我想要实现的基本例子。

感谢您的帮助

    class Program
    {
        private static List<IJob> _jobs; 

        static void Main(string[] args)
        {
            LoadJobs();

            foreach (var job in _jobs)
            {
                job.Run();
            }

            Console.ReadKey();
        }

        static void LoadJobs()
        {
            _jobs = new List<IJob>();

            var jobsPath = Directory.GetFiles(@"C:\Jobs\");

            foreach (var file in jobsPath)
            {
                var assembly = Assembly.LoadFrom(file);

                foreach (var type in assembly.GetExportedTypes())
                {
                   var instance = Activator.CreateInstance(type);
                   var job = instance as IJob;

                    if(job != null)
                        _jobs.Add(job);
                }
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

foreach (var type in assembly.GetExportedTypes().Where(t => t.IsAssignableFrom(typeof (IJob))))
{
    var job = Activator.CreateInstance(type) as IJob;
    if(job != null) _jobs.Add(job);
}