C# C-在运行时创建在dll中找到的对象的实例
我的代码有问题,无法找出问题所在 目标是搜索一些实现接口的dll,然后创建它们的实例 这就是我现在所做的:C# C-在运行时创建在dll中找到的对象的实例,c#,C#,我的代码有问题,无法找出问题所在 目标是搜索一些实现接口的dll,然后创建它们的实例 这就是我现在所做的: List<ISomeInterface> instances = new List<ISomeInterface>(); String startFolder = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "FolderWi
List<ISomeInterface> instances = new List<ISomeInterface>();
String startFolder = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location), "FolderWithDLLS");
foreach (var f in Directory.EnumerateFiles(startFolder, "*.dll", SearchOption.AllDirectories))
{
var assembly = Assembly.ReflectionOnlyLoadFrom(f);
var types = assembly.GetTypes();
foreach (var type in types)
{
if (type.GetInterface("ISomeInterface") != null)
{
//line bellow shows errors about some invalid arguments
//default constructor doesn't need any parameters.
instances.Add(Activator.CreateInstance(type));
}
}
assembly = null;
}
错误:方法System.Collections.Generic.List.AddISomeInterface的最佳重载匹配具有一些无效参数。CreateInstancetype返回一个对象
Add需要一个接口
所以你需要投下它
instances.Add((ISomeInterface)Activator.CreateInstance(type));
您有一个强类型列表,但CreateInstance方法返回对象,所以您需要强制转换它
instances.Add((ISomeInterface)Activator.CreateInstance(type));
你能发布你得到的全部错误吗?捕获异常{//谁在乎?}你。你真的在乎。`抓住例外{//谁在乎?}`我在乎。。。如果你不关心你的异常,你怎么能认真地要求别人关心呢?为什么你不简单地使用类型的AssemblyQualifiedname,然后简单地用Activator.CreateInstance调用它?伙计们,我把它放在这里只是为了好玩,问题不在于它,为什么这么讨厌?我甚至没有编译这段代码,视频显示了我发布的错误。我不知道我怎么会错过它。在我的国家有点晚了。非常感谢。