code_junkie

How to properly cast objects created through reflection

Nov 10th, 2011
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.73 KB | None | 0 0
  1. loop through assemblies
  2. loop through types in assembly
  3. // Filter out unwanted types
  4. if (!type.IsClass || type.IsNotPublic || type.IsAbstract )
  5. continue;
  6. // This successfully created the right object
  7. object o = Activator.CreateInstance(type);
  8. // This threw an Invalid Cast Exception or returned null for an "as" cast
  9. // even though the object implemented IPlugin
  10. IPlugin i = (IPlugin) o;
  11.  
  12. using System.Runtime.Remoting;
  13. ObjectHandle oh = Activator.CreateInstance(assembly.FullName, type.FullName);
  14. // This worked as I intended
  15. IPlugin i = (IPlugin) oh.Unwrap();
  16. i.DoStuff();
  17.  
  18. IPluginModule pluginModule = (IPluginModule)Activator.CreateInstance(curType);
  19.  
  20. Activator.CreateInstance(type, true);
Add Comment
Please, Sign In to add comment