简体   繁体   中英

Can I treat an object as implementing an interface from reflection?

I am trying to load types from a DLL that all implement an interface. I want to be able to get the types from the DLL, create and instance of each type and then treat each type as if it implements the interface. I have written a basic example below of what I'm trying to achieve.

Thanks for your help

    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);
                }
            }
        }
    }
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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM