繁体   English   中英

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

[英]Instantiating a class in C# from a string

我正在使用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;
    }

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

尝试使用类的全名(包括名称空间),不要使用“ .cs”部分。 例如: YourApp.Services.YourWebViewService

如果您的字符串包含完全限定的类型名称,则可以创建实例。

Type.GetType不使用带有文件名的字符串。 它采用类名或结构名。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM