简体   繁体   English

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

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

I'm working on a windows phone 7 application which uses Silverlight. 我正在使用Silverlight的Windows Phone 7应用程序上工作。 What I'm looking to do is create a new instance of a class given a string containing the name of the correct class I would like to create. 我想做的是给一个包含要创建的正确类名的字符串创建一个类的新实例。 Below is the snipit of code I'm referring to and I am trying to use it to create the new instance. 下面是我所引用的代码片段,我试图用它来创建新实例。 I know from debugging that serviceClass contains the correct string and if I add ".cs" to it, it would now correspond directly to one of the classes I have, so why isn't it being created? 通过调试,我知道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;
    }

Any help at all or any suggestions would be greatly appreciated. 任何帮助或任何建议将不胜感激。 Thanks for your time! 谢谢你的时间!

Try using the full name of the class (namespace included), without the ".cs" part. 尝试使用类的全名(包括名称空间),不要使用“ .cs”部分。 For example: YourApp.Services.YourWebViewService 例如: YourApp.Services.YourWebViewService

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

Type.GetType doesn't take a string with a file name. Type.GetType不使用带有文件名的字符串。 It takes a class name or a struct name. 它采用类名或结构名。

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

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