gpt4 book ai didi

c# - 无法通过反射将类型传递给泛型类

转载 作者:行者123 更新时间:2023-11-30 12:48:34 24 4
gpt4 key购买 nike

我有一个类具有以下...

public class Client<T> : IClient where T : IClientFactory, new()
{
public Client(int UserID){}
}

和另一个实现 IClientFactory 的类

public class Client : IClientFactory

如果引用了 dll,那么我可以很容易地执行此操作来实例化它。

var data = new namespace.Client<namespace.OtherDLL.Client>(1);

但很明显,如果我尝试使用加载的程序集执行此操作,这将失败,因为它不知道类型。我一直在阅读以使用反射来做到这一点。但我试图实现这些想法,但都失败了。这是一篇关于它的文章。 Can I pass a type object to a generic method?

Assembly myDllAssembly = Assembly.LoadFile(project.Path + project.Assembly);

Type type = myDllAssembly.GetType("Migration.Application.Client");

var data = new namespace.Client<type>(1);

这方面的任何帮助都会很棒,因为我正在尝试仅使用一个配置文件来让我在 DLL 准备好提供给客户端时轻松删除 DLL,并且只需修改配置文件即可使一切正常运行。

最佳答案

您需要使用反射调用该方法:

var type = typeof(Client<>).MakeGenericType(type);
var data = (IClient)Activator.CreateInstance(type, 1)

关于c# - 无法通过反射将类型传递给泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13806546/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com