动态加载DLL类并转换为IMyInterface失败求助
Hey Matthew, let's break down why your cast from the dynamically loaded class to IMyInterface is returning null—even though you can find the target type. This is a common pitfall with dynamic assembly loading, so here are the top causes and fixes to try:
1. Mismatched Interface Assemblies
This is the most frequent culprit. The CLR treats interfaces as distinct types if they come from different assembly instances, even if the code is identical.
- What's happening: If the shared DLL containing
IMyInterfacereferenced by your main application is not the exact same file (or same strong name/version) as the one referenced byMyClass.dll, the CLR will see two separateIMyInterfacetypes. So even if your class implements "its" version of the interface, it won't match the one in your main app. - Fixes:
- Ensure both your main application and
MyClass.dllproject reference the same physical copy of the shared DLL (e.g., use a shared project, a single NuGet package, or copy the DLL to a common output directory). - If you're using strong-named assemblies, verify the version number, public key token, and culture match exactly across all references.
- Double-check for accidental duplicate
IMyInterfacedefinitions (e.g., if you copied the interface code into your main app instead of referencing the shared DLL).
- Ensure both your main application and
2. The Class Doesn't Actually Implement the Interface
It's easy to miss a subtle mismatch that breaks the interface implementation:
- What's happening: Your class might declare it implements
IMyInterface, but has mismatched method signatures (e.g., wrong return type, missing parameters, or case differences), or it's an abstract class that can't be instantiated. If you're using theasoperator for casting, this will return null instead of throwing an exception. - Fixes:
- Confirm the class definition looks like this:
public class MyConcreteClass : IMyInterface(both the class and interface must bepublic). - Verify all interface methods are implemented correctly—check for explicit implementations that might not be visible, but note that explicit implementation shouldn't cause a cast to return null (it just means you can't call the methods directly on the class instance).
- Add a check in your code to confirm the type actually implements the interface:
If this returnsvar targetType = assembly.GetType("MyNamespace.MyConcreteClass"); bool implementsInterface = typeof(IMyInterface).IsAssignableFrom(targetType); Console.WriteLine($"Does type implement IMyInterface? {implementsInterface}");false, you know the issue is with the class's interface implementation.
- Confirm the class definition looks like this:
3. Assembly Loading Context Conflicts
The way you load MyClass.dll can cause the CLR to load duplicate copies of the shared interface DLL:
- What's happening: Using
Assembly.LoadFileorAssembly.LoadFromcan load assemblies outside the standard application context, leading the CLR to load a new copy of the shared DLL (instead of reusing the one your main app already loaded). This creates the same type mismatch issue as scenario 1. - Fixes:
- Prefer
Assembly.Load(passing the assembly's full name) instead ofLoadFrom/LoadFile—this lets the CLR's assembly binding mechanism resolve dependencies properly. - If you must use
LoadFrom, ensure the shared DLL is in the same directory asMyClass.dll, or add its directory to the application's probing path. - Debug the assembly locations to confirm they match:
If the paths differ, you're dealing with duplicate assembly loads.var targetType = assembly.GetType("MyNamespace.MyConcreteClass"); var interfaceFromTarget = targetType.GetInterfaces() .FirstOrDefault(i => i.FullName == typeof(IMyInterface).FullName); Console.WriteLine($"Main app interface assembly: {typeof(IMyInterface).Assembly.Location}"); Console.WriteLine($"Loaded class's interface assembly: {interfaceFromTarget?.Assembly.Location}");
- Prefer
4. Visibility or Access Issues
If your interface or class isn't accessible, the cast can fail silently when using as:
- What's happening: If
IMyInterfaceis notpublic, or the target class is notpublic, theasoperator will return null because the cast isn't allowed. (A direct cast would throw anInvalidCastException, which is more informative.) - Fixes:
- Make sure
IMyInterfaceis declared aspublic interfaceand the class ispublic class. - Replace the
ascast with a direct cast to get a meaningful exception:
The exception message will give you clearer insight into why the cast isn't working.try { var myInstance = (IMyInterface)Activator.CreateInstance(targetType); } catch (InvalidCastException ex) { Console.WriteLine($"Cast failed: {ex.Message}"); }
- Make sure
内容的提问来源于stack exchange,提问作者Matthew

