c# - 从字符串中检索类型

标签 c# generics types

我有这门课:

namespace Ns1.Ns2.Domain
{
    public class Process
    {
        private IIndex IndexBuilderConcr { get; set; }

        public Processo(String processType) {
            IndexBuilderConcr = new UnityContainer().RegisterType<IIndex, *>().Resolve<IIndex>();
        }
    }
}

这里我有一个采用String的构造函数。该字符串表示应替换第 8 行 * 符号的类型。 我用谷歌搜索了一下,但没有运气。

最佳答案

您需要做的是按照 James S 建议的方式获取类型,但是您需要以与调用 Method<resolvedProcessType> 略有不同的方式将该值传递到方法中。无效:

var type = Type.GetType("Some.Name.Space." + processType);

var methodInfo = typeof(UnityContainer).GetMethod("RegisterType");

// this method's argument is params Type[] so just keep adding commas
// for each <,,,>
var method = methodInfo.MakeGenericMethod(IIndex, type);

// we supply null as the second argument because the method has no parameters
unityContainer = (UnityContainer)method.Invoke(unityContainer, null);

unityContainer.Resolve<IIndex>();

关于c# - 从字符串中检索类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23063945/

相关文章:

c# - Windows 窗体中的 Button_click

c# - 了解移位运算符

c# - 解析 "DateTime.Now"?

java - 列表包含类型不安全的方法

swift - 为什么要限制带有 Self 或 associatedtype 的协议(protocol)?

c# - ASP.Net MVC TryUpdateModel() 等效于在 Windows 应用程序中使用

java - 如何理解泛型方法中选择了什么类型而不是T?

.net - 从名称实例化泛型的最佳方法是什么?

angular - 在 typescript 中定义抽象类的类型

c++ - 如何在 C++ 中为非常量和本地数据伪造依赖类型?