gpt4 book ai didi

c# - 从字符串实例化 C# 中的类

转载 作者:太空宇宙 更新时间:2023-11-03 20:26:20 25 4
gpt4 key购买 nike

我正在开发一个使用 Silverlight 的 Windows Phone 7 应用程序。我想要做的是创建一个类的新实例,给定一个字符串,其中包含我想要创建的正确类的名称。下面是我所指的代码片段,我正在尝试使用它来创建新实例。我从调试中知道 serviceClass 包含正确的字符串,如果我向它添加“.cs”,它现在将直接对应于我拥有的类之一,那么为什么不创建它呢?

WebViewService foundService; //From above
....
....
services.TryGetValue(mode, out foundService); //Find service
if (foundService == null)
{
string serviceClass;
serviceRegistry.TryGetValue(mode, out serviceClass); //Find serviceClass
if (serviceClass != null) //create new web service if one is found
{
try
{
//TODO: This is not working properly, should create an instance of some child class of WebViewService
foundService = (WebViewService)System.Activator.CreateInstance(Type.GetType(serviceClass+".cs"));
services.Add(mode, foundService);
}
catch
{
//But instead it always ends up here with ArgumentNullExeption
}
}
}
return foundService;
}

任何帮助或任何建议将不胜感激。感谢您的宝贵时间!

最佳答案

如果你的字符串包含fully qualified type name然后你可以创建实例。

关于c# - 从字符串实例化 C# 中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10457358/

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