作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个类具有以下...
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/
我是一名优秀的程序员,十分优秀!