You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

动态加载DLL类并转换为IMyInterface失败求助

Troubleshooting Null Cast When Dynamically Loading Interface Implementation

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 IMyInterface referenced by your main application is not the exact same file (or same strong name/version) as the one referenced by MyClass.dll, the CLR will see two separate IMyInterface types. 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.dll project 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 IMyInterface definitions (e.g., if you copied the interface code into your main app instead of referencing the shared DLL).

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 the as operator 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 be public).
    • 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:
      var targetType = assembly.GetType("MyNamespace.MyConcreteClass");
      bool implementsInterface = typeof(IMyInterface).IsAssignableFrom(targetType);
      Console.WriteLine($"Does type implement IMyInterface? {implementsInterface}");
      
      If this returns false, you know the issue is with the class's interface implementation.

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.LoadFile or Assembly.LoadFrom can 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 of LoadFrom/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 as MyClass.dll, or add its directory to the application's probing path.
    • Debug the assembly locations to confirm they match:
      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}");
      
      If the paths differ, you're dealing with duplicate assembly loads.

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 IMyInterface is not public, or the target class is not public, the as operator will return null because the cast isn't allowed. (A direct cast would throw an InvalidCastException, which is more informative.)
  • Fixes:
    • Make sure IMyInterface is declared as public interface and the class is public class.
    • Replace the as cast with a direct cast to get a meaningful exception:
      try
      {
          var myInstance = (IMyInterface)Activator.CreateInstance(targetType);
      }
      catch (InvalidCastException ex)
      {
          Console.WriteLine($"Cast failed: {ex.Message}");
      }
      
      The exception message will give you clearer insight into why the cast isn't working.

内容的提问来源于stack exchange,提问作者Matthew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:19:17