通过反射将类强制转换为基接口导致异常
我通过反射动态加载 .NET 程序集,并获取它包含的所有类(目前是一个)。之后,我尝试将该类转换为我 100% 确定该类实现的接口,但收到此异常: 无法将 System.RuntimeType 类型的对象转换为 MyInterface 类型
MyDLL.dll
public interface MyInterface
{
void MyMethod();
}
MyOtherDLL.dll
public class MyClass : MyInterface
{
public void MyMethod()
{
...
}
}
public class MyLoader
{
Assembly myAssembly = Assembly.LoadFile("MyDLL.dll");
IEnumerable<Type> types = extension.GetTypes().Where(x => x.IsClass);
foreach (Type type in types)
{
((MyInterface)type).MyMethod();
}
}
我已经删除了所有不需要的代码。这基本上就是我所做的。我在这个问题中看到安迪回答了问题似乎和我的一样,但我无论如何也无法解决它。
I'm loading a .NET assembly dinamically via reflection and I'm getting all the classes that it contains (at the moment one). After this, I'm trying to cast the class to an interface that I'm 100% sure the class implements but I receive this exception: Unable to cast object of type System.RuntimeType to the type MyInterface
MyDLL.dll
public interface MyInterface
{
void MyMethod();
}
MyOtherDLL.dll
public class MyClass : MyInterface
{
public void MyMethod()
{
...
}
}
public class MyLoader
{
Assembly myAssembly = Assembly.LoadFile("MyDLL.dll");
IEnumerable<Type> types = extension.GetTypes().Where(x => x.IsClass);
foreach (Type type in types)
{
((MyInterface)type).MyMethod();
}
}
I have stripped out all the code that is not necessary. This is basically what I do. I saw in this question that Andi answered with a problem that seems the same mine but I cannot anyway fix it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在尝试将
Type
类型的 .NET Framework 对象强制转换为您创建的接口。Type
对象未实现您的接口,因此无法对其进行强制转换。您应该首先创建对象的特定实例,例如通过使用Activator
,如下所示:CreateInstance
方法具有其他可能适合您需求的重载。You are trying to cast a .NET framework object of type
Type
to an interface that you created. TheType
object does not implement your interface, so it can't be cast. You should first create a specific instance of your object, such as through using anActivator
like this:The
CreateInstance
method has other overloades that may fit your needs.