gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:46:50 24 4
gpt4 key购买 nike

我有这门课:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com