【问题标题】:Having trouble passing type to a generic class with reflection无法通过反射将类型传递给泛型类
【发布时间】:2012-12-11 02:18:19
【问题描述】:

我有一个具有以下内容的课程...

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,并且只需修改配置文件以使事情正常运行。

【问题讨论】:

标签: c# generics reflection


【解决方案1】:

你需要使用反射调用方法:

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

【讨论】:

  • 我想你的意思是MakeGenericType
  • @dbaseman:对我来说var data = namespace.Client&lt;type&gt;(1); 看起来像是一个方法调用。但你是对的,剩下的问题看起来更像是他忘记了new...
  • Assembly myDllAssembly = Assembly.LoadFile(project.Path + project.Assembly); Type genericClassType = myDllAssembly.GetType("GEC.Migration.SWOCS.Application.Client"); var type = GEC.Migration.FileManager.GetType("Client").MakeGenericMethod(genericClassType); var data = (IClient)Activator.CreateInstance(type, userID); GetType() 好像有问题说找不到
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-15
  • 1970-01-01
  • 1970-01-01
  • 2016-02-12
  • 1970-01-01
  • 1970-01-01
  • 2021-12-04
相关资源
最近更新 更多