如何将带有类名的字符串转换为泛型可以接受的类

本文关键字:泛型 转换 字符串 | 更新日期: 2023-09-27 18:19:09

我有以下代码:

var something = UnityContainer.Resolve<IService<Package>>();

这工作得很好,因为Package是我定义的类的名称,它是由Unity设置和映射的。然而,在我的应用程序中,我的类作为字符串参数进入方法。像这样:

public void Update(string className) {
var something = UnityContainer.Resolve<IService<Package>>();

是否有一种方法,我可以采取className字符串,并使用它在上述泛型就像一个类?

如何将带有类名的字符串转换为泛型可以接受的类

我从来没有使用过UnityContainer,但我认为你可以解决一个组件传递一个类型作为参数。你可以这样做:

Type packageType = Type.GetType(className);
Type openGenericType = typeof(IService<>);
Type myClosedType = openGenericType.MakeGenericType(packageType);
var something = UnityContainer.Resolve(myClosedType); 

你可以这样做

Assembly asm = Assembly.GetExecutingAssembly();
var t = asm.GetType("ConsoleApplication1.Test");

其中ConsoleApplication1是程序集名Test是类名

Type类中有一个名为"MakeGenericType"的实例化方法,有了它,你可以像下面这样传递你想要用于泛型参数的类型:

    public void Update(string className)
    {
        var targetType = Type.GetType(className);
        var serviceType = typeof(IService<>);
        var genericParam = serviceType.MakeGenericType(targetType);
        var unityType = typeof(UnityContainer);
        var resolve = unityType.GetMethod("Resolve");
        var targetMethod = resolve.MakeGenericMethod(genericParam);
        var something = targetMethod.Invoke(null, new[] { genericParam });
        //...

Resolve方法主要是由UnityContainerExtensions类定义的扩展方法。Resolve唯一的重载是UnityContainer的实例方法