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

标签 c# generics reflection

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

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/

相关文章:

c# - 在程序启动时从文本文件加载

c# - 为什么 Encoding.ASCII != ASCIIEncoding.Default 在 C# 中?

c# - 有没有更有效的方法在我的数据库中插入数据数组? Asp.net-core + Dapper

c# - 从数组填充列表

java - 如何将非通用接口(interface)扩展为通用接口(interface)?

java - 使用 String 和方法重载创建对象

c# - 通过 VS 2010 中的多个项目级联 native dll 资源的副本

python - 动态添加len方法?

reflection - Rebol为什么不换新线?类似地对待换行关键字和换行符吗?

ios - 如何处理 GenericClass<Any> 进行抽象