开发者

Why is Assembly.GetType() not finding my class?

Code excerpt:

var a = Assembly.LoadFile("MyAssembly.dll");
var t = a.GetType("MyNamespace.MyClass", false);
Debug.Assert(t != null); // fails

Assembly.LoadFile() is loading the assembly without any trouble, but Assembly.GetType() is returning null, even though I have ver开发者_高级运维ified that MyNamespace.MyClass is present and correctly spelled.

Any other ideas why this is happening?


In the line

var t = a.GetType("MyNamespace.MyClass", false);

set that boolean to true so you get an exception that could explain the problem. For various problem situations you get separate exceptions, see MSDN or the new docs.


The actual underlying problem was that MyAssembly.dll has another dependency on OtherAssembly.dll. Once I include a reference to OtherAssembly.dll in the calling assembly, everything works fine.


// Retrieve all classes that are typeof SomeClassOrInterface

List<Type> myTypes = assembly.GetTypes().Where(typeof(SomeClassOrInterface).IsAssignableFrom).ToList();

// Loop thru them or just use Active.CreateInstance() of the type you need

myTypes.ForEach(myType => {
    SomeClassOrInterface instance = Activator.CreateInstance(myType) as SomeClassOrInterface;                           
});

This code sample works under .NET 4

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜